Is there a way to cancel/override a delay()?

  1. What do you want to achieve? Keep it simple and clear!

I am working on a combat system. Whenever the player gets hit, it cannot attack. I am doing this by using a BoolValue named “GotHit” and set the value to true when the player gets hit and then after a second, the value becomes false. I am using delay().

  1. What is the issue? Include screenshots / videos if possible!

Unfortunately, it does not work as expected. When I punch the dummy twice, the value becomes false and then true immediately and then false again. Basically, the delay does not stop and/or get overrided by a new delay().

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

I have tried looking for solutions on the DevHub but I did not find any threads that could have a similar problem.

Code:

GOT_HIT.Value = true
delay(0.5, function()
	GOT_HIT.Value = false
end)

Are there any alternatives to delay() or any way to cancel a delay()? Advanced thank you for those whoever helps.

2 Likes

I would recommend using a debounce, this way it doesn’t trigger multiple times when being called, making the delay prominent

local isTouched = false  -- Declare debounce variable

if not isTouched then  -- Check that debounce variable is not true
isTouched = true  -- Set variable to true

-- Your code here

isTouched = false -- Set variable to false
2 Likes

Yes I use something that I invented called an FID (function ID) - basically this is how it works:

function doThis()
    local thisFID = os.clock()
    globalFID = thisFID

    delay(2, function()
        if thisFID ~= globalFID then
            return
        end
        
        print("Not canceled!")
    end)
end


doThis()
 wait(0.5)
doThis()
 wait(0.5)
doThis()

-- prints("Not canceled!") once
1 Like

I really don’t understand why people store data in values rather than modules. But anyways, to be able to override it’s easier to use number values rather than boolean.

I’m curious what does this do?
was this a typo for “~=“, or is this just something I’ve never heard of?

Oh my bad i meant to do ~= but pressed the wrong key lol

I actually found a way to make it work as expected. :sweat_smile:

if GOT_HIT.Value == false then
	GOT_HIT.Value = true
	spawn(function()
		wait(0.5)
		GOT_HIT.Value = false
	end)
else
	spawn(function()
		repeat wait() until GOT_HIT.Value == false
		GOT_HIT.Value = true
		wait(0.5)
		GOT_HIT.Value = false
	end)
end

I used spawn() in order to keep the whole script running and prevent wait() from stopping the script. Works as intended now!

As for those who replied, still, thank you for helping me. :smiley:

1 Like