Cancel Timer Error? (SOLVED)

#1

I created a timer… I cancel the timer when a value > 70 but for some reason while it stops it throws this error afterwards continuously as if the timer is still firing…

bad argument #1 to ‘cancel’ (number expected, got nil)

stack traceback:
[C]: in function ‘cancel’

The use of a keyboard command is just placeholder to fire the timer function so I can test the underlying code but maybe it’s a byproduct of too many key presses firing? That’s why I gated it with the barvalue=25

if action_id == hash("HotKeyJ") and barvalue==25 then

	local pbar_timer = timer.delay(0.05, true, function()

		barvalue = barvalue + 1

		if barvalue > 70 then	
			stopped = timer.cancel(pbar_timer)		
		end

		UIUpdatedProgressBar("HealthBar1", Values.Value[1].Label, barvalue, 0, 100, 70, "comments", "healthicon.png")
		
	end)
end
0 Likes

#2

I think the problem is that you’re using pbar_timer in the function that defines it. You should be able to use

	local pbar_timer = timer.delay(0.05, true, function(_,pbar_timer,_)

		barvalue = barvalue + 1

		if barvalue > 70 then	
			stopped = timer.cancel(pbar_timer)		
		end

		UIUpdatedProgressBar("HealthBar1", Values.Value[1].Label, barvalue, 0, 100, 70, "comments", "healthicon.png")
		
	end)

The second argument of the timer callback function is the timer handle (the same thing that gets returned from timer.delay). You can read more about it in the timer API doc.

1 Like

#3

Exactly! It is recommended to use this when cancelling the timer from within the callback function. Unless you declare your timer function slightly differently in which case it should work:

local pbar_timer
pbar_timer = timer.delay(0.05, true, function()
	...
	timer.cancel(pbar_timer)		
	...
end)
0 Likes

#4

ok code changed and it’s working fine. Thanks for the help @JustAPotota and @britzl

0 Likes