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

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

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

local Events_Folder = Tool.Events

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

local Stun_Time = 3

local Stun_Playing = false
local Parried = false

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
		Parry_Value.Value = 1
		Parry_Value.Value = 0
		Parried = false
1 Like

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

local cooldown

if cooldown then

cooldown = task.spawn(function()
	print("cooldown ended")

You can also use task.delay() instead:

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

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")
--and to cancel it

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")