Implementing a pause and resume mechanism for javascript loop execution

前端 未结 2 1781
逝去的感伤
逝去的感伤 2020-12-10 21:34

I\'m trying to provide a pause and resume functionality to a loop with recursive calls. I\'m using \"setTimeout\" and \"clearTimeout\" functions for this...

When a u

相关标签:
2条回答
  • 2020-12-10 21:43

    Back in 2012 I wrote a snippet of code for delta timing in JavaScript, which uses setTimeout and has start and stop functions: https://gist.github.com/aaditmshah/2056987

    See the demo:

    var button = document.querySelector("button");
    var div = document.querySelector("div");
    
    var running = false;
    
    var number = 1;
    
    var timer = new DeltaTimer(function () {
      div.innerHTML = number++;
    }, 1000);
    
    button.addEventListener("click", function () {
      if (running) {
        timer.stop();
        button.innerHTML = "Start";
        running = false;
      } else {
        timer.start();
        button.innerHTML = "Stop";
        running = true;
      }
    });
    
    function DeltaTimer(render, interval) {
        var timeout;
        var lastTime;
    
        this.start = start;
        this.stop = stop;
    
        function start() {
            timeout = setTimeout(loop, 0);
            lastTime = Date.now();
            return lastTime;
        }
    
        function stop() {
            clearTimeout(timeout);
            return lastTime;
        }
    
        function loop() {
            var thisTime = Date.now();
            var deltaTime = thisTime - lastTime;
            var delay = Math.max(interval - deltaTime, 0);
            timeout = setTimeout(loop, delay);
            lastTime = thisTime + delay;
            render(thisTime);
        }
    }
    <button>Start</button>
    <div></div>

    Hope that helps.

    0 讨论(0)
  • 2020-12-10 21:51

    I was misunderstanding the clearTimeout function. I thought the callback (calback in setTimeout(...)) would be executed immediately after clearTimeout is called. But the callback is not executed after clearTimeout is called...

    The working JS code is,

    var array = [1,2,3,4,5,6,7];
    var timer;
    var i=0;
    
    function execute(){
         timer = setTimeout(function () {
                   alert(array[i]);
                   i++;
                   if (array.length > i){
                       execute();
                   }
               }, 1000);
    }
    
    $('document').ready(function(){
    
        $('#loop_controler').click(function(){
            if ($(this).text() == 'pause'){
              clearTimeout(timer);
              $(this).text('resume');
            } else {
              execute();
              $(this).text('pause');
            }
        });
    
        execute(array,0);
    });
    
    0 讨论(0)
提交回复
热议问题