How to end current function when meet certain condition?

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

I want to end a current function that is running under a certain condition

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

I want to make sure the function ends as soon as the condition is met (not end it by checking after every second), but I do not know if there is some existing method or code that does this.

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

Since I know that wait() provides the smallest amount of time of 0.03 second yield, I used a for loop to calculate each and every 0.03 seconds to check whether that certain condition is met. This solution I came up with is similar to this developer’s problem’s solution How can i break a function while it's running? - #10 by CheekySquid, but of course, I wanted to end the moment that condition is hit.

local function someCode()
     while true do
     -- Long list of code here
     -- The following code below demonstrate the cooldown equivalent to wait(seconds)
     for i = 1, 20 * RELOAD_TIME do -- 0.05 * 20 is equivalent to 1 second
		wait(0.05)
		if IS_EQUIPPED == false or RELOADING_STATUS == false then
			-- end this entire function
			return
		end
     end
end

Look at this thread here, seems basic:

Instead of while true do
try
while IS_EQUIPPED == true or RELOADING_STATUS == true

I know how to run a function inside a script, but I was asking if there was a way to end the script as soon as the condition is met without having to check every 0.05 seconds through a loop.

I was thinking of this, but this would lead the code to crash due to time exhaustion.

You could add a task.wait() inside of the loop? It waits until the next render step so it’s faster than wait() is

Not if you put the wait(.05) in the while IS_EQUIPPED… loop.

Oh, I forgot about that, I can definitely do that. I still have to wait 0.05 seconds rather than end the function the moment the condition changes.

1 Like

I forgot task.wait() existed. I believe task.wait() yield the code by 0.015 seconds? Could I still make it end in an instant some other way?

Checking the condition in the while loop should already do the trick as the code won’t run anymore since it fails that check.

However, if you really want it to be instant, I think you could either use events or spawn the function as a thread (using task.spawn()) and then cancel it using task.cancel() once the condition changes?

I guess I will try this out and combine it with your task.wait() to check as soon as possible.