Constantly lowering a script's variable to zero before stopping

A simple idea, I understand how I could do this but I’d like to know if there’s any better way to do it.

While variable > 0 do
variable -= 0.1
wait(0.1)
end

I’m worried that while this could work, that it’d be inefficient as hell due to the script having to constantly repeat these things, alongside this running alongside other functions. If this is the best way to do it, so be it, but I believe that there’s a better method right?

1 Like

You can do something like this:

local RunService = game:GetService("RunService")

local runConnection = nil
local valueToChange = 1
local lastUpdate = 0

runConnection = RunService.Stepped:Connect(function(_, deltaTime: number)
	if (os.clock() - lastUpdate) < 0.1 then
		return
	end
	
	valueToChange = math.clamp(valueToChange - deltaTime, 0, math.huge)
	lastUpdate = os.clock()
	
	print(valueToChange)
	
	if valueToChange <= 0 then
		return runConnection:Disconnect()
	end
end)
2 Likes

Would you recommend your script over the one I posted?

Yeah, I would recommend my script over the one in the post.

My apologies for needing to take up more of your time, but could you tell me what your script does better? Is it optimization, consistency, or something else entirely?

  1. It does not yield the script
  2. Using a Stepped connection is better for performance than using while loops
  3. Also, wait() is deprecated and has been superseded by task.wait()
1 Like

Alright. This script has been very useful, but has the issue of not being able to restart, even if valueToChange is increased again later on.

I could try teaking the code to look like this:

	if (os.clock() - lastUpdate) < 0.1  or valueToChange <= 0 then
		return
	end

But would there be any issues with this change?

Its very funny how I was just going to type something similar to that until I saw your post XD Nice job man!

Whenever you want to stop the loop, you can do

runConnection:Disconnect()

And then restart the loop again

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