Javascript - 暂停setInterval()

时间:2014-01-22 08:36:35

标签: javascript setinterval

如何使用Javascript暂停和恢复setInterval()函数?

例如,也许我有一个秒表来告诉你你在网页上看到的秒数。有一个“暂停”和“恢复”按钮。 clearInterval()在这里不起作用的原因是因为如果用户在第40秒和第800毫秒点击“暂停”按钮,当他点击“恢复”按钮时,经过的秒数必须在200毫秒后增加1。如果我在timer变量上使用clearInterval()函数(单击暂停按钮时),然后再次对timer变量使用setInterval()函数(单击恢复按钮时),经过的秒数将增加1仅在1000毫秒后,这会破坏秒表的准确性。

那我该怎么做?

8 个答案:

答案 0 :(得分:87)

您可以使用标记来跟踪状态:

var output = $('h1');
var isPaused = false;
var time = 0;
var t = window.setInterval(function() {
  if(!isPaused) {
    time++;
    output.text("Seconds: " + time);
  }
}, 1000);

//with jquery
$('.pause').on('click', function(e) {
  e.preventDefault();
  isPaused = true;
});

$('.play').on('click', function(e) {
  e.preventDefault();
  isPaused = false;
});
h1 {
    font-family: Helvetica, Verdana, sans-serif;
    font-size: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Seconds: 0</h1>
<button class="play">Play</button>
<button class="pause">Pause</button>

这就是我要做的,我不确定你是否可以实际暂停setInterval。

注意:此系统非常简单,对于不需要高精度的应用程序非常有效,但它不会考虑时间间隔之间经过的时间:如果您在半秒后单击暂停,然后单击玩你的时间将关闭半秒钟。

答案 1 :(得分:8)

你不应该测量间隔功能的时间。而只是节省计时器启动时的时间,并在计时器停止/暂停时测量差异。仅使用setInterval更新显示的值。因此,无需暂停计时器,您将以这种方式获得最佳准确度。

答案 2 :(得分:6)

虽然@Jonas Giuro说的是对的:

  

你不能暂停setInterval函数,你可以将它停止(clearInterval),或让它运行

另一方面,可以使用approach @VitaliyG suggested模拟此行为:

  

您不应该在间隔函数中测量时间。而只是节省计时器启动时的时间,并在计时器停止/暂停时测量差异。仅使用setInterval更新显示的值。

var output = $('h1');
var isPaused = false;
var time = new Date();
var offset = 0;
var t = window.setInterval(function() {
  if(!isPaused) {
    var milisec = offset + (new Date()).getTime() - time.getTime();
    output.text(parseInt(milisec / 1000) + "s " + (milisec % 1000));
  }
}, 10);

//with jquery
$('.toggle').on('click', function(e) {
  e.preventDefault();
  isPaused = !isPaused;
  if (isPaused) {
    offset += (new Date()).getTime() - time.getTime();
  } else {
    time = new Date();
  }

});
h1 {
    font-family: Helvetica, Verdana, sans-serif;
    font-size: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Seconds: 0</h1>
<button class="toggle">Toggle</button>

答案 3 :(得分:4)

为什么不使用更简单的方法?添加一个类!

只需添加一个告诉间隔不要做任何事情的类。例如:在悬停时。

var i = 0;
this.setInterval(function() {
  if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
    console.log('Counting...');
    $('#counter').html(i++); //just for explaining and showing
  } else {
    console.log('Stopped counting');
  }
}, 500);

/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
    $(this).addClass('pauseInterval');
  },function() { //mouse leave
    $(this).removeClass('pauseInterval');
  }
);

/* Other example */
$('#pauseInterval').click(function() {
  $('#counter').toggleClass('pauseInterval');
});
body {
  background-color: #eee;
  font-family: Calibri, Arial, sans-serif;
}
#counter {
  width: 50%;
  background: #ddd;
  border: 2px solid #009afd;
  border-radius: 5px;
  padding: 5px;
  text-align: center;
  transition: .3s;
  margin: 0 auto;
}
#counter.pauseInterval {
  border-color: red;  
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<p id="counter">&nbsp;</p>
<button id="pauseInterval">Pause</button></p>

我一直在寻找这种快速简便的方法,所以我发布了几个版本,尽可能多地介绍它。

答案 4 :(得分:1)

我的简单方法:

table #mytable td {
    background: #eee;
}

使用方法:

function Timer (callback, delay) {
  let callbackStartTime
  let remaining = 0

  this.timerId = null
  this.paused = false

  this.pause = () => {
    this.clear()
    remaining -= Date.now() - callbackStartTime
    this.paused = true
  }
  this.resume = () => {
    window.setTimeout(this.setTimeout.bind(this), remaining)
    this.paused = false
  }
  this.setTimeout = () => {
    this.clear()
    this.timerId = window.setInterval(() => {
      callbackStartTime = Date.now()
      callback()
    }, delay)
  }
  this.clear = () => {
    window.clearInterval(this.timerId)
  }

  this.setTimeout()
}

代码编写迅速且未进行重构,如果您希望我改进代码并提供ES2015版本(类),请提高答案的等级。

答案 5 :(得分:1)

我写了一个简单的ES6类,可能会派上用场。 受https://stackoverflow.com/a/58580918/4907364答案

的启发
export class IntervalTimer {
    private callbackStartTime;
    private remaining= 0;
    private paused= false;
    public timerId = null;
    private readonly _callback;
    private readonly _delay;

    constructor(callback, delay) {
        this._callback = callback;
        this._delay = delay;
    }

    pause() {
        if (!this.paused) {
            this.clear();
            this.remaining = new Date().getTime() - this.callbackStartTime;
            this.paused = true;
        }
    }

    resume() {
        if (this.paused) {
            if (this.remaining) {
                setTimeout(() => {
                    this.run();
                    this.paused = false;
                    this.start();
                }, this.remaining);
            } else {
                this.paused = false;
                this.start();
            }
        }
    }

    clear() {
        clearInterval(this.timerId);
    }

    start() {
        this.clear();
        this.timerId = setInterval(() => {
            this.run();
        }, this._delay);
    }

    private run() {
        this.callbackStartTime = new Date().getTime();
        this._callback();
    }
}

用法非常简单,

const interval = new IntervalTimer(console.log(aaa), 3000);
interval.start();
interval.pause();
interval.resume();
interval.clear();

答案 6 :(得分:0)

我知道这个线程很旧,但这可能是另一个解决方案:

var do_this = null;

function y(){
   // what you wanna do
}

do_this = setInterval(y, 1000);

function y_start(){
    do_this = setInterval(y, 1000);
};
function y_stop(){
    do_this = clearInterval(do_this);
};

答案 7 :(得分:0)

以下代码提供了一种暂停计时器的精确方法。

工作方式:

当计时器暂停后恢复时,它会使用单个timeout生成一个校正周期,该周期将考虑暂停偏移量(计时器在两个周期之间暂停)。校正周期结束后,它将使用常规setInteval安排以下周期,并继续正常执行周期。

这允许暂停/恢复计时器,而不会丢失同步。

代码:

function Timer(_fn_callback_ , _timer_freq_){
    let RESUME_CORRECTION_RATE = 2;

    let _timer_statusCode_;
    let _timer_clockRef_;

    let _time_ellapsed_;        // will store the total time ellapsed
    let _time_pause_;           // stores the time when timer is paused
    let _time_lastCycle_;       // stores the time of the last cycle

    let _isCorrectionCycle_;
 
    /**
     * execute in each clock cycle
     */
    const nextCycle = function(){
        // calculate deltaTime
        let _time_delta_        = new Date() - _time_lastCycle_;
        _time_lastCycle_    = new Date();
        _time_ellapsed_   += _time_delta_;

        // if its a correction cicle (caused by a pause,
        // destroy the temporary timeout and generate a definitive interval
        if( _isCorrectionCycle_ ){
            clearTimeout( _timer_clockRef_ );
            clearInterval( _timer_clockRef_ );
            _timer_clockRef_    = setInterval(  nextCycle , _timer_freq_  );
            _isCorrectionCycle_ = false;
        }
        // execute callback
        _fn_callback_.apply( timer, [ timer ] );
    };

    // initialize timer
    _time_ellapsed_     = 0;
    _time_lastCycle_     = new Date();
    _timer_statusCode_   = 1;
    _timer_clockRef_     = setInterval(  nextCycle , _timer_freq_  );


    // timer public API
    const timer = {
        get statusCode(){ return _timer_statusCode_ },
        get timestamp(){
            let abstime;
            if( _timer_statusCode_=== 1 ) abstime = _time_ellapsed_ + ( new Date() - _time_lastCycle_ );
            else if( _timer_statusCode_=== 2 ) abstime = _time_ellapsed_ + ( _time_pause_ - _time_lastCycle_ );
            return abstime || 0;
        },

        pause : function(){
            if( _timer_statusCode_ !== 1 ) return this;
            // stop timers
            clearTimeout( _timer_clockRef_ );
            clearInterval( _timer_clockRef_ );
            // set new status and store current time, it will be used on
            // resume to calculate how much time is left for next cycle
            // to be triggered
            _timer_statusCode_ = 2;
            _time_pause_       = new Date();
            return this;
        },

        resume: function(){
            if( _timer_statusCode_ !== 2 ) return this;
            _timer_statusCode_  = 1;
            _isCorrectionCycle_ = true;
            const delayEllapsedTime = _time_pause_ - _time_lastCycle_;
            _time_lastCycle_    = new Date( new Date() - (_time_pause_ - _time_lastCycle_) );

            _timer_clockRef_ = setTimeout(  nextCycle , _timer_freq_ - delayEllapsedTime - RESUME_CORRECTION_RATE);

            return this;
        } 
    };
    return timer;
};


let myTimer = Timer( x=> console.log(x.timestamp), 1000);
<input type="button" onclick="myTimer.pause()" value="pause">
<input type="button" onclick="myTimer.resume()" value="resume">

代码源:

此Timer是advanced-timer的修改和简化版本,list1 = [4,1,3] list2 = [2,5,2] list1_greater_list2_value = [a > b for a,b in zip(list1,list2)] print ("list1-value greater then list2-value:", list1_greater_list2_value) 是我自己创建的js库,具有更多功能。

  

完整的库和文档位于NPMGITHUB