Cancelling a Thread with task.wait() inside of it

Hello! Recently I had a need to create a task.wait(5) timer, that can also be cancelled upon a Remote Event being fired.

That last part is sorted out, however I have no idea on how to create a Thread with a task.wait(5) inside of it, so that I can execute and cancel it when needed.

If context is necessary: I’d like to create a timer whenever player goes out of the Safe Zone, and if they happen to still be outside of that zone after timer runs out - they get kicked. However, Timer has to reset if a player manages to get into a safe zone again.

Code:

...
thread = task.delay(5, function()
		task.wait(5)
end)

RS.Events.OutsideSafezone.OnServerEvent:Connect(function(player)
	task.spawn(thread)
	RS.Events.OutsideSafezoneServer:FireClient(player)
end)

RS.Events.GotIntoSafeZone.OnServerEvent:Connect(function(player)
	task.cancel(thread)
	RS.Events.GotIntoSafeZoneServer:FireClient(player)
end)
...

I think this works

thread = function(player)

	task.wait(10)

	RS.Events.OutsideSafezoneServer:FireClient(player)
end

RS.Events.OutsideSafezone.OnServerEvent:Connect(function(player)
	
	task.spawn(function()

		thread(player)
	end)
end)

RS.Events.GotIntoSafeZone.OnServerEvent:Connect(function(player)

	task.cancel(thread)

	RS.Events.GotIntoSafeZoneServer:FireClient(player)
end)
1 Like

Doesn’t throw out any errors, but also doesn’t work entirely. It does not create a thread, which task.delay does

Use coroutines, they are the best option for this.

Example:

local Thread = function(Player)
	task.wait(10)
	RS.Events.OutsideSafezoneServer:FireClient(player)
end

local RunningThread = nil

RS.Events.OutsideSafezone.OnServerEvent:Connect(function(player)
	
	RunningThread = coroutine.create(Thread)
	coroutine.resume(RunningThread)

end)

RS.Events.GotIntoSafeZone.OnServerEvent:Connect(function(player)

	coroutine.close(RunningThread)
	RunningThread = nil

	RS.Events.GotIntoSafeZoneServer:FireClient(player)
end)
3 Likes

Works perfectly fine, although a slight issue persists that before player enters a safe zone - there’s no running thread, causing it to try and close a non-existant thread. Any fixes for that?

Yes, I forgot to add a if statement to prevent that from happening.

Just add this

if RunningThread == nil then return end
3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.