Cocos2dx 3.x Lua 中使用定时器有两种方式:
(1)self:scheduleUpdateWithPriorityLua(update, priority)
> 参数一:刷新函数
> 参数二:刷新优先级
其中 self 为 Node类 的子类。
该方法默认为每帧都刷新一次,无法自定义刷新时间间隔。
(2)scheduler:scheduleScriptFunc(update, inteval, false)
> 参数一:刷新函数
> 参数二:每次刷新的时间间隔
> 参数三:是否只执行一次。false为无限次。
其中 scheduler 为定时器管理:cc.Director:getInstance():getScheduler()
推荐使用第二种方式,因为比较通用。
local function timeLack()
--北京时间2015-12-27 0:0:0 1451145600
return 1451145600 - tonumber(activeLayer:GetServerTime())
end
local function updateLeftTime(f)
local t = timeLack()
if t > 0 then
local strLeftTime = string.format("%02d:%02d:%02d", math.modf(t % (60 * 60 * 24) / (60 * 60)), math.modf(t % (60 * 60) / 60), t % (60 * 60) % 60)
local d = math.modf(t / (60 * 60 * 24))
local strLeftDay = ""
if d > 0 then
strLeftDay = string.format("%d", d) .. getLocalString("day", appLoc) .. ""
end
textContent:setString(getLocalString("activeTime", appLoc) .. strLeftDay .. strLeftTime)
else
textContent:setVisible(false)
end
end
local schedule_updateLeftTime = nil
local scheduler = cc.Director:getInstance():getScheduler() --
schedule_updateLeftTime = scheduler:scheduleScriptFunc(updateLeftTime, 1.0, false) --时间调度器
local function onNodeEvent(event) --退出事件停止调用定时器
if event == "exitTransitionStart" then
if schedule_updateLeftTime then
scheduler:unscheduleScriptEntry(schedule_updateLeftTime)
schedule_updateLeftTime = nil
end
end
end
--创建退出时候监听
textContent:registerScriptHandler(onNodeEvent)
updateLeftTime(0)