首页 正文
314

Js倒计时方法

  • yiqingpeng
  • 2016-03-18
  • 0
  •  
用js写了一个按秒倒计时的方法,主要运用了闭包的特性。
/**
*seconds  int  倒计时的总秒数
*func  function 每一秒触发的回调
*/
function timeWalker(seconds, func){
    this.tid=0;
    this.start = function(){
        this.tid = setInterval((function(sec, obj){
            return function(){
                typeof func ==='function' && func(sec);
                if(sec<=1) {
                    clearInterval(obj.tid);  
                }else{
                    --sec;
                }
            };
        })(seconds, this), 1000);
    };
    this.stop = function(){
        clearInterval(this.tid);
    }
    this.start();
}
使用方法: new timeWalker(50, function(sec){console.log(sec);});

正在加载评论...