"timer.cancel()" doesn't work when trying to stop a function called with "timer.performWithDelay()".

It says invalid timer (expected a table but got a nil)

local autoToggle = false local autoButton = display.newCircle( ccx, ccy, 10) autoButton:setFillColor(0.07) autoButton.x = cw - 60 autoButton.y = -10 local function auto() local shape = display.newCircle( ccx, 30, 5 ) shape:setFillColor(1,1,1) physics.addBody( shape, "dynamic", {density=1, radius=6}) local function removeCircle() display.remove(shape) end timer.performWithDelay( 10000, removeCircle) end local function autoToggleFunction() if ( autoToggle == false ) then local spawnTimer = timer.performWithDelay(10, auto, -1) autoToggle = true elseif ( autoToggle == true ) then timer.cancel( spawnTimer ) autoToggle = false end end autoButton:addEventListener("tap", autoToggleFunction)

Trying to execute function autoToggleFunction() with delays when the shape(autoButton) is “tapped”.

And stop the timer when it is clicked again.

It says invalid timer. How do I fix this?

Also, is there any ways to simplify this code?

Scope.

spawnTimer is local to the funciton and is created/init’d every time you enter that function.

If you declare spawnTimer outside of the function, it will work.

–john

OMG! THANK YOU SO MUCH JOHN!!!

Glad I could help!  :slight_smile:

Scope.

spawnTimer is local to the funciton and is created/init’d every time you enter that function.

If you declare spawnTimer outside of the function, it will work.

–john

OMG! THANK YOU SO MUCH JOHN!!!

Glad I could help!  :slight_smile: