# How would i stop this loop?

So i have this camera shake in a local script. In a while true loop how would i stop the loop after 5 seconds?

``````game.ReplicatedStorage.Shake.OnClientEvent:Connect(function()
local humanoid = game.Players.LocalPlayer.Character.Humanoid
while true do
local x = math.random(-50,50)/50
local y = math.random(-50,50)/50
local z = math.random(-50,50)/50
humanoid.CameraOffset = Vector3.new(x,y,z)
wait()

end
end)
``````
1 Like
``````game.ReplicatedStorage.Shake.OnClientEvent:Connect(function()
local humanoid = game.Players.LocalPlayer.Character.Humanoid
local x = true
while x = true do

local x = math.random(-50,50)/50
local y = math.random(-50,50)/50
local z = math.random(-50,50)/50
humanoid.CameraOffset = Vector3.new(x,y,z)
wait()

end
end)
``````

Then make X false when you want to stop.

You could probably use os.time to check.

Something like this should work:

``````local init = os.time()
while init - os.time() < 5 do
local x = math.random(-50,50)/50
local y = math.random(-50,50)/50
local z = math.random(-50,50)/50
humanoid.CameraOffset = Vector3.new(x,y,z)
wait()
end
``````

Depending on if something is going to happen after loop you can use either “break” or “return”.
For the 5 seconds you can compare a tick() before and after

I think this would be the solution

``````--Variables
local Clock		=	0
local Running	=	false

--Shaking Function
game.ReplicatedStorage.Shake.OnClientEvent:Connect(function()

--If it's not looping a shake at the time, start a loop and set the variables
if not Running then
Running	=	true			--Mark the script as running so the script knows a loop is being ran at the time
Clock	=	os.time() + 5	--Set the ending time 5 seconds from now

--The loop will go on until the ending time is below the current time
local Humanoid = game.Players.LocalPlayer.Character.Humanoid
while os.time() < Clock do
Humanoid.CameraOffset = Vector3.new(
math.random(-50, 50) / 50,
math.random(-50, 50) / 50,
math.random(-50, 50) / 50
)
wait()
end

--Eventually after the looping has stopped, set the variable so the script knows it's no longer running
Running	=	false		--Mark the script as no longer running
else
--If it's looping a shake already, set the ending time 5 seconds from now
Clock	=	os.time() + 5
end
end)
``````
2 Likes

That would break the loop after one wait()/one tick. That will only change the camera offset once.

``````local Humanoid = game.Players.LocalPlayer.Character.Humanoid
while true do --Loop starts
--Camera offset changes once
Humanoid.CameraOffset = Vector3.new(math.random(-50, 50) / 50, math.random(-50, 50) / 50, math.random(-50, 50) / 50)
--Waits 1 tick
wait()
--Breaks immediately in the first loop, ending the loop after 1 tick instead of 5 seconds
break
end
``````

The topic was already solved so there is no need for more answers.

All that is doing is just offsetting the camera once, waits 5 seconds doing nothing and then breaks the loop.

There is already a solution to this topic: