0

this is my script to change text every second until it reaches the second eleven. How can I make a function that I can pause?

For example to stop at second five.

<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 Answers1

0

Instead of trying to pause execution and cause the browser to be stuck in some CPU-intensive loop as some might suggest, the optimal way would be to make use of timers. Below is an example using 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);

When the timer starts, and on each tick, it sets counter_tick to the current time in milliseconds. Each tick of the timer, and when the timer is stopped, it calculates how much time has passed since the last tick and adds that to your counter. To "pause" your timer you simply clear it. An example of this can be found here: http://codepen.io/anon/pen/jactn

Lynxy
  • 117
  • 2
  • 8