为JavaScript循环执行实现暂停和恢复机制 [英] Implementing a pause and resume mechanism for javascript loop execution

查看:38
本文介绍了为JavaScript循环执行实现暂停和恢复机制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过递归调用为循环提供暂停和恢复功能.我为此使用了"setTimeout"和"clearTimeout"函数.

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

当用户单击暂停"按钮时,计时器将设置为无限时间(最大可能).当用户单击恢复"按钮时,应该通过"clearTimeout"调用清除超时.但是超时永远不会清除.我怎么了?

When a user clicks the button "pause", the timer is set to infinite time (maximum possible). When the user clicks the button "resume", the timeout is supposed to be cleared with "clearTimeout" call. But the timeout is never cleared. What is my mistake?

先谢谢您.

JFIDDLE DEMO

HTML:

<button id="loop_controler">pause</button>

JS:

var array = [1,2,3,4,5,6,7];
var pause = false;
var timer;

function execute(array,i){
    var pauseTime = 0;
    if (pause){
        pauseTime = 2147483647;  //max value for timeout     
    }
    timer = setTimeout(function(){        //set timer
           setTimeout(function () {       
               alert(array[i]);           //this timeout gives a constant delay
               if (array.length > i)      //(just to give enough time to users to click button)
                   execute(array,i+1);
           }, 1000);
    }, pauseTime);
    console.log('set ' + timer);
}

$('document').ready(function(){

    $('#loop_controler').click(function(){
        if ($(this).text() == 'pause'){
          pause = true;
          $(this).text('resume');
        } else {
          clearTimeout(timer);           //clear timer
          console.log('clear ' + timer);
          pause = false;
          $(this).text('pause');
        }
    });

    execute(array,0);
});

推荐答案

我误解了clearTimeout函数.我认为回调(在setTimeout(...)中的回调)将在调用clearTimeout之后立即执行.但是调用clearTimeout之后不会执行回调.

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

有效的JS代码是

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);
});

这篇关于为JavaScript循环执行实现暂停和恢复机制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆