Nanfeng

Notes on software development, code, and curious ideas

Scheduling and Cancelling Timers in Cocos2d-x Lua

Environment: Cocos2d-x 3.17
Language: Lua

Use quick-Cocos2d-x’s scheduler helper to run a callback periodically:

1
2
3
4
5
local scheduler = require("framework.scheduler")

local timerHandle = scheduler.scheduleGlobal(function()
-- Work to perform every 0.2 seconds.
end, 0.2)

Cancel it with the returned handle:

1
2
3
4
if timerHandle then
scheduler.unscheduleGlobal(timerHandle)
timerHandle = nil
end

Store the handle on the object that owns the timer and cancel it when the scene or component exits. Otherwise a global callback may keep running and access nodes that have already been destroyed.

+