How to cancel wait()?

Hello my issue is that I want to animate the value of how quickly customers are spawned based on how many tables a user has in their resturant.

For example:

  • Quickly spawn customers until 60% of tables are filled
  • Slowly spawn customers until 100% of tables are filled

The issue is that if I call the function multiple time I want any previous running functions to stop playing. I can do this using a variable check but it can be unpredictable with wait().

function slow spawn
  for I=10,0,-1 do
    spawnPet()
    task.Wait(10)
  end
end

Then if I connect slow spawning to play whenever their table stats change (for optomization) I call the function again. In this case I want to cance the previous running function

local canGo = false

function slowSpawn
  for I=10,0,-1 do
    if canGo then
      spawnPet()
      task.Wait(10)
    else
      break
    end
  end
end

-- table value changes
slowSpawn()

task.Wait(1)

-- table value changes
slowSpawn()

in this case I cannot just set canGo to false then true to cancel the previous function as it only checks it canGo every 10 seconds.

Note

excuse any code typos and invalid indenting as I wrote this on my phone. Thank you for your understanding.

2 Likes

You should use tick for this, for example:

local cancelwait = false
local OldTick = tick()
local CurrentTick = tick()
repeat task.wait() until (CurrentTick - OldTick) >= 5(waittime) or cancelwait = true
OldTick = CurrentTick

I do not know if this is 100% working but its from my old game and it worked fine

you can use task library with spawn and cancel methods to cancel code (and waiting)

1 Like

Okay I noticed the cance() function in the library. Would it be something like

Function doStuff

local example = task.Spawn(doStuff)
task.Cance(example)

Yes, task.spawn() returns thread that you can put into task.cancel() to stop it

You cannot cancel wait on its own. But you can cancel a thread.

1 Like

Thanks for the help! This will be very useful!

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