关于js倒计时的模板 可在多个项目中复用

来源:互联网 发布:网易新闻 推荐算法 编辑:程序博客网 时间:2024/06/18 02:35

/**
* 使用美术字的倒计时 需要 fnt文件预加载
* 使用的时候通过 cc.eventManager.dispatchCustomEvent(USER_TIME_COUNT_SET_TIME, 5) 设置倒计时时间
* cc.eventManager.dispatchCustomEvent(USER_TIME_COUNT_START) 使得倒计时开启
* cc.eventManager.dispatchCustomEvent(USER_TIME_COUNT_STOP) 使得倒计时暂停
* 在需要得到倒计时结束的类里去
* cc.eventManager.addCustomListener(USER_TIME_COUNT_FINISH, function(event){
cc.log(‘app 获取了定时器传回的结束’)
})
*/
var USER_TIME_COUNT_SET_TIME = “USER_TIME_COUNT_SET_TIME” //设置倒计时时间
var USER_TIME_COUNT_START = “USER_TIME_COUNT_START” //开始倒计时
var USER_TIME_COUNT_PAUSE = “USER_TIME_COUNT_PAUSE” //停止倒计时
var USER_TIME_COUNT_FINISH = “USER_TIME_COUNT_FINISH” //倒计时结束 由定时器抛出
var TimeCount = cc.Layer.extend({
EventArr:[USER_TIME_COUNT_SET_TIME, USER_TIME_COUNT_START, USER_TIME_COUNT_PAUSE],
Label_time:null,
Label_Position:null,
Count_Time:0,
ScheduleRun:false,
Start_DateTime:0,
ctor:function(){
this._super()
this.init()
},
init:function(){
this.Label_Position = cc.p(cc.winSize.width>>1,cc.winSize.height*0.95); //调整倒计时坐标

    this.Label_time = new cc.LabelBMFont("hello",res.bmFont);    this.Label_time.setPosition(this.Label_Position)    this.addChild(this.Label_time)    cc.log(Date.now())    this.scheduleUpdate()    for(var index in this.EventArr){        var event = this.EventArr[index]        cc.eventManager.addCustomListener(event, this.onGetCustom.bind(this))    }},onGetCustom:function(event){    var data = event.getUserData();    switch (event.getEventName()){        case USER_TIME_COUNT_SET_TIME:            cc.log('设置了倒计时时间:',data)            this.Count_Time = data            this.Label_time.setString(this.Count_Time)            break        case USER_TIME_COUNT_START:            cc.log('启动了倒计时:')            this.Start_DateTime = Date.now()            this.ScheduleRun = true            break        case USER_TIME_COUNT_PAUSE:            cc.log('停止了倒计时')            this.ScheduleRun = false            break    }},update:function(){    if(this.ScheduleRun){        if(Date.now() - this.Start_DateTime>=1000){            this.Count_Time --;            this.Label_time.setString(this.Count_Time)            this.Start_DateTime += 1000            if(0 == this.Count_Time){                this.timeStop()                cc.eventManager.dispatchCustomEvent(USER_TIME_COUNT_FINISH)            }        }    }},timeStop:function(){    cc.log('倒计时结束了:')    this.ScheduleRun = false},onExit:function(){    this.unscheduleUpdate()    this.removeAllChildren(true)    for(var index in this.EventArr){        var event = this.EventArr[index]        cc.eventManager.removeCustomListeners(event)    }}

})
这个文件可以单独写成一个js类 。然后添加到想要添加的场景里面去

     引用方法  :var Time = new TimeCount();               this.addChild(Time)  就可以给创建的这个类引用到想要引用的场景里面去。
0 0
原创粉丝点击