Question about while loops

Will the loop below run every 2 minutes or will it run a bunch that I’m not aware of?

while true do
    task.wait(120)
    print("2 minutes have passed")
end

Is there a more efficient way?

1 Like

Using wait is not ideal, since it yields the whole script. Check out this post for more info on it. As to your post, it will work, however i wud advise against it. Also, I would recommend using a custom wait such as this.

It looks basic, as using loops they use basic code, this is the code I do:


-- 2 minutes loop with remaining
for i = 1,2 do
	if i == 2 then
		print("2 minutes done")
	else
		print(i.." minute done")
	end
	task.wait(60)
end

-- 2 minutes loop while true do loop with break.
while true do
	task.wait(160)
	print("2 minutes has passed")
    break -- breaks the loop to stop
end

Some how 2 minutes loop using while true do loop, it yields the whole script, the above is my own script, only use if you want, is all yours.

Passing with while true do uses infinite loop and you can’t stop it without break
Just like spamming prints on output which it’s very yields using while true do

What @Mystxry12 said, is it recommended by that than me.

1 Like

umm task.wait() is basically the same as RunService.Heartbeat:Wait() or RunService.Stepped:Wait()(thus different from the normal wait()). So it is not as bad practice really(at least as far as i’m aware). Correct me if i’m wrong please.

It yields the thread it’s called on, like task.wait and all the custom implementations, not the entire script

local totalTime = os.clock()
while true do
	task.wait()
	print(os.clock() - totalTime)
	if (os.clock() - totalTime) >= 120 then
		print("done")
		break
	end
end

probably not the best way to do it but I still wanted to share this way. I tested another way which is using a RenderStepped which again is not necessary but I like testing this like this and it ended up being more accurate stopping milleseconds before the number
10 but the other example with the while true do stopped milleseconds after the number 10.

local RunService = game:GetService("RunService")

local totalTime = os.clock()
RunService.RenderStepped:Connect(function()
	task.wait()
	if (os.clock() - totalTime) >= 120 then
		print("done")
	else
		print(os.clock() - totalTime)
	end
end)

honestly I would just keep it simple at the end of the day :

while true do 
task.wait(120)
print("done")
-- and then you can either break the loop or let it countinue depending on what you want
break -- break stops the loop from running again its pretty self explainable "break" so it breaks the loop.

end

Performance wise I am not entirely sure which one is the most efficient but I am assuming using RenderStepped for something like this would be inefficient (correct me if I am wrong) so I would just use something between the first one and the last one.

Ahh yess, my bad sry abt it. ignore