How do I Stop task.wait() When Needed?


I’m wondering how I can stop task.wait() when needed in my code. I have a spawning system and it waits the respawn time each time a player dies before they respawn. The reason I need to stop it is because if the player leaves, there is no need to keep yielding the code, so I cancel the respawn.

I have tried using a repeat loop to measure the time passed to simulate a single task.wait() and made it stop if it reached it’s goal or the player left. And while that works, I’m wondering if this is the best way to do it or if there’s a better way. Here’s my code:

local function ManageRespawn(Player, Character)
	local Humanoid = CharacterModule:GetHumanoid(Character)

		local TimePassed = 0
		local StepInterval = 0.100

			TimePassed += StepInterval
		until TimePassed >= Players.RespawnTime or not Player.Parent

		if not Player.Parent then return end


Any help will be appreciated!


You can’t “stop” a task.wait() from yielding.

However, you can make each interval really short to minimise the delay when you actually want it to stop.

local start = tick()
repeat task.wait() until tick() - start > StepInterval or ...

You can insert the condition you want to stop the wait.


I see. A very smart method which works better, thank you!

1 Like