Anyone know a proper way to stop a function? For example, if I call a function and there is a timer and the player I don’t know maybe clicks a part and now I want the function to stop in its tracks. So therefore the function is technically done and nothing after where the function was will playout.
I tried using a disconnect line like people said but I’ve had zero luck.
local function tp()
You can read about it all here task | Documentation - Roblox Creator Hub
But in general using task.wait() is more efficient than normal wait(), task.spawn() creates a function on a new thread which means it doesnt yield the code, instead it runs both the function and the rest of the code at the same time. task.cancel() stops a task you created, and task.delay() basically does same thing as task.spawn() but you also add a timer after how long it will run the function you provided.
Yes! So what I’m trying to do is when a player sits down(seat) it will fire a function which will teleport the player in per say 20 seconds. The catch is if the player gets up. I would want the entire function to be canceled so that the timer wouldn’t run down. It would just be finished without completing. If the function wouldn’t end, the player would be teleported as if they didn’t get up from that seat.
local CurrentOccupant = nil
local CurrentThread = nil
if Seat.Occupant then
CurrentOccupant = Seat.Occupant
CurrentThread = task.delay(20, function()
if CurrentThread then
CurrentThread = nil
CurrentOccupant = nil
To explain further on what @wf_sh has posted; task.delay() is a function itself which immediately run. You could write a wrapper to prevent the countdown from immediately starting
local seated = true
local function StartTeleporting()
if not seated then
print("User is not sitting here")
StartTeleporting() -- The countdown starts here, and this allows you to start a new countdown any time you call this function.