我该如何暂停javascript功能

时间:2014-05-13 14:54:02

标签: javascript

这是我的脚本每秒更改文本,直到它到达第二个十一。我怎样才能创建一个可以暂停的功能?

例如,在第二个五点停止。

<script>
    (function () {
    var nativeSetTimeout = window.setTimeout;

    window.bindTimeout = function (listener, interval) {
        function setTimeout(code, delay) {
            var elapsed = 0,
                h;

            h = window.setInterval(function () {
                    elapsed += interval;
                    if (elapsed < delay) {
                        listener(delay - elapsed);
                    } else {
                        window.clearInterval(h);
                    }
                }, interval);
            return nativeSetTimeout(code, delay);
        }

        window.setTimeout = setTimeout;
        setTimeout._native = nativeSetTimeout;
    };
    }());
    window.bindTimeout(function (t) {
    $('.arc').html('<canvas id="mycanvas" width="80" height="80"></canvas>');
    $('#vot_ch_s').html((t/1000) + "s");}, 1000);


    window.setTimeout(function () {$('.arc').html('<canvas id="mycanvas" width="80" height="80"></canvas>');}, 11000);

    </script>

1 个答案:

答案 0 :(得分:0)

而不是试图暂停执行并导致浏览器陷入某些CPU密集型循环中,而有些人可能会建议,最佳方法是使用计时器。以下是使用setInterval的示例:

var counter = 0, counter_tick, counter_interval;

var timerTick = function() {
  var now = Date.now();
  counter += now - counter_tick;
  counter_tick = now;

  /* do your work here */
  $('#counter').html(counter/1000);
};

var startTimer = function() {
  counter_tick = Date.now();
  counter_interval = setInterval(timerTick, 100);
}

var stopTimer = function() {
  clearInterval(counter_interval);
  timerTick();
}

$('#start').on('click', startTimer);
$('#stop').on('click', stopTimer);

当计时器启动时,每次打勾时,它会将counter_tick设置为当前时间(以毫秒为单位)。计时器的每个滴答,当计时器停止时,它计算自上次滴答以来经过的时间并将其添加到您的计数器。到&#34;暂停&#34;你的计时器,你只需清除它。可在此处找到此示例:http://codepen.io/anon/pen/jactn