How to stop timers when transitioning to different storyboard scene

The game I am creating has an enemy spawn every 3 seconds.  When I transition from the scene where the enemys are spawning to the main menu there are alot of glitches, like to enemy spawning at the main menu. I think this would be fixed If I canceled my timers in the function scene:exitScene( event ). I’ve read the docs and I am still confused on what to put in for the arguments for timer.cancel().

[lua]

local function spawnEnemy()

    local enemy = display.newImage(“enemy.png”)

    --(A bunch of physics properties)

    timer.performWithDelay(3000, spawnEnemy)

end

function scene:exitScene( event )

    timer.cancel(spawnEnemy)

    storyboard.removeAll( )

end

[/lua]

Thank you

Hi @ytduglepvp,

When using timer.cancel(), you need to point to the timer itself, not the function which was triggered when the timer executed. One way to handle this is to add each timer instance to another table, like this:

[lua]

local spawnTimers = {}  --declare new table to hold the timer references, and make sure it’s properly scoped

local function spawnEnemy()

    local enemy = display.newImage(“enemy.png”)

    --(A bunch of physics properties)

    spawnTimers[#spawnTimers+1] = timer.performWithDelay(3000, spawnEnemy)

end

[/lua]

Then, later, backwards-loop through the table and cancel all of them:

[lua]

for t = #spawnTimers, 1, -1 do

    timer.cancel( spawnTimers[t] )

    spawnTimers[t] = nil

end

[/lua]

Hope this helps,

Brent

Thank you, this worked.

Hi @ytduglepvp,

When using timer.cancel(), you need to point to the timer itself, not the function which was triggered when the timer executed. One way to handle this is to add each timer instance to another table, like this:

[lua]

local spawnTimers = {}  --declare new table to hold the timer references, and make sure it’s properly scoped

local function spawnEnemy()

    local enemy = display.newImage(“enemy.png”)

    --(A bunch of physics properties)

    spawnTimers[#spawnTimers+1] = timer.performWithDelay(3000, spawnEnemy)

end

[/lua]

Then, later, backwards-loop through the table and cancel all of them:

[lua]

for t = #spawnTimers, 1, -1 do

    timer.cancel( spawnTimers[t] )

    spawnTimers[t] = nil

end

[/lua]

Hope this helps,

Brent

Thank you, this worked.