开发者社区> 问答> 正文

js中计时器怎么暂停

js中计时器怎么暂停

展开
收起
云计算小粉 2018-05-10 20:00:25 5477 0
2 条回答
写回答
取消 提交回答
  • function Timer(callback, delay) {

    var timerId, start, remaining = delay;
    //暂停
    this.pause = function() {
        window.clearTimeout(timerId);
        remaining -= new Date() - start;
    };
    //继续
    this.resume = function() {
        start = new Date();
        window.clearTimeout(timerId);
        timerId = window.setTimeout(callback, remaining);
    };
    
    this.resume();

    }

    var timer = new Timer(function() {

    alert("Done!");

    }, 1000);

    timer.pause();
    // Do some stuff...
    timer.resume();

    2019-07-17 22:11:23
    赞同 展开评论 打赏
  • 先创建定时器,拿到定时器句柄,再清楚该定时器

    1. 单次定时
    // 创建定时器, 仅一秒后执行一次
    var timer = setTimeout(function(){ console.log('something') }, 1000)
    
    // 清除定时器
    clearTimeout(timer)
    1. 循环定时
    // 创建定时器, 每秒执行一次
    var timer = setInterval(function(){ console.log('something') }, 1000)
    
    // 清除定时器
    clearInterval(timer)
    2019-07-17 22:11:23
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
JavaScript函数 立即下载
Delivering Javascript to World 立即下载
编程语言如何演化-以JS的private为例 立即下载