How to cancel task.wait()

i’m trying to make a combat system but i’ve ran into the issue where i don’t know how to cancel task.wait() function if something changed

--//Services
local Run_Service = game:GetService("RunService")
local Replicated_Storage = game:GetService("ReplicatedStorage")

--//Tool
local Tool = script.Parent.Parent
local Sounds = Tool.Sounds:GetChildren()

--//Events
local Events_Folder = Tool.Events

local Damage_Remote = Events_Folder.DamageRemote
local Parry_Remote = Events_Folder.ParryRemote

--//Values
local Stun_Time = 3

local Stun_Playing = false
local Parried = false

--//Particles
local Combat = Replicated_Storage.Combat
local Gore = Combat.Gore

--| Main Script |--
function Parry(Player)
	local Parry_Value = Player.Character:WaitForChild("Block")
		if Parried == false then
		Parry_Value.Value = 2
		Parried = true
		print(Parry_Value.Value)
		
		Parry_Value.Value = 1
		print(Parry_Value.Value)
		else
		Parry_Value.Value = 0
		Parried = false
		print(Parry_Value.Value)
end
end
1 Like

You can’t cancel task.wait() itself, but you can cancel a thread in which its called:

local cooldown

if cooldown then
    task.cancel(cooldown)
end

cooldown = task.spawn(function()
	task.wait(3)
	print("cooldown ended")
end)

You can also use task.delay() instead:

cooldown = task.delay(3,function()
	print("cooldown ended")
end)

With task.cancel(FunctionName) you can cancel an already running task, also keep in mind you should check if its running and cancel it before starting a new one, otherwise you will trigger it multiple times.
If you want to have multiple of them you can make a table and do this instead:

cooldown[1] = task.delay(3,function()
	print("cooldown ended")
end)
--and to cancel it
task.cancel(cooldown[1])
7 Likes

Not sure because I’m not that good with parallel luau, but since this is another thread, wouldn’t it just not yield the script?

1 Like

promises are going to be your best bet with something like this.

1 Like

Yes, you would just need to put the rest of the code within the task. If its intended to continue the code when wait is cancelled, then you could just have a function holding rest of the code and call the function when wait ends, or when its cancelled.

1 Like

You can resume a task.wait with task.spawn before its meant to, no need for messy promises here

Just dont depend on the return because task.spawning a task.wait changes the return

local co = coroutine.running()
task.delay(3, task.spawn, co, "thread resumed early")

print(task.wait(5))
3 Likes