Javascript 如何在 FOR 循环中创建暂停或延迟?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10058753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:40:12  来源:igfitidea点击:

How to create pause or delay in FOR loop?

javascriptjqueryfor-loop

提问by jams

I am working on a website, where I need to create a pause or delay.
So please tell me How to create pause or delay in forloop in javascriptor jQuery

我在一个网站上工作,我需要在那里创建一个暂停或延迟。
所以请告诉我如何在for循环中创建暂停或延迟javascriptjQuery

This is a test example

这是一个测试示例

 var s = document.getElementById("div1");
 for (i = 0; i < 10; i++) {
     s.innerHTML = s.innerHTML + i.toString();
     //create a pause of 2 seconds.
  }

采纳答案by jams

I tried all one, but I think this code is better one, it is very simple code.

我尝试了所有一种,但我认为这段代码更好,它是非常简单的代码。

var s = document.getElementById("div1");
var i = 0;
setInterval(function () {s.innerHTML = s.innerHTML + i.toString();  i++;}, 2000);

回答by Guffa

You can't use a delay in the function, because then the change that you do to the element would not show up until you exit the function.

您不能在函数中使用延迟,因为这样您对元素所做的更改在退出函数之前不会显示。

Use the setTimeoutto run pieces of code at a later time:

setTimeout稍后使用来运行代码段:

var s = document.getElementById("div1");
for (i = 0; i < 10; i++) {

  // create a closure to preserve the value of "i"
  (function(i){

    window.setTimeout(function(){
      s.innerHTML = s.innerHTML + i.toString();
    }, i * 2000);

  }(i));

}

回答by nicosantangelo

var wonderfulFunction = function(i) {
   var s = document.getElementById("div1"); //you could pass this element as a parameter as well
   i = i || 0;
   if(i < 10) {
      s.innerHTML = s.innerHTML + i.toString();

      i++;
      //create a pause of 2 seconds.
      setTimeout(function() { wonderfulFunction(i) }, 2000);          
   }
}

//first call
wonderfulFunction(); //or wonderfulFunction(0);

You can't pause javascript code, the whole language is made to work with events, the solution I provided let's you execute the function with some delay, but the execution never stops.

你不能暂停 javascript 代码,整个语言都是为了处理事件,我提供的解决方案让你延迟执行函数,但执行永远不会停止。

回答by SKing7

if you want to create pause or delay in FOR loop,the only real method is

如果你想在 FOR 循环中创建暂停或延迟,唯一真正的方法是

while (true) {
    if( new Date()-startTime >= 2000) {
        break;
    }
}

the startTime is the time before you run the while but this method will cause the browsers become very slow

startTime 是运行之前的时间,但是这种方法会导致浏览器变得非常慢

回答by zatatatata

The following code is an example of pseudo-multithreading that you can do in JS, it's roughly an example of how you can delay each iteration of a loop:

以下代码是您可以在 JS 中执行的伪多线程示例,它大致是如何延迟循环的每次迭代的示例:

var counter = 0;

// A single iteration of your loop
// log the current value of counter as an example
// then wait before doing the next iteration
function printCounter() {
    console.log(counter);
    counter++;
    if (counter < 10)
        setTimeout(printCounter, 1000);
}

// Start the loop    
printCounter();

回答by BishopZ

While several of the other answers would work, I find the code to be less elegant. The Frame.jslibrary was designed to solve this problem exactly. Using Frame you could do it like this:

虽然其他几个答案都可以,但我发现代码不太优雅。该Frame.js库的目的是要准确地解决这个问题。使用 Frame 你可以这样做:

var s = document.getElementById("div1");
for (i = 0; i < 10; i++) {
   Frame(2000, function(callback){ // each iteration would pause by 2 secs
      s.innerHTML = s.innerHTML + i.toString();
      callback();
   }); 
}
Frame.start();

In this case, it is nearly the same as the examples that use setTimeout, but Frame offers a lot of advantages, especially if the you are trying to do multiple or nested timeouts, or have a larger JS application that the timeouts need to work within.

在这种情况下,它与使用 setTimeout 的示例几乎相同,但是 Frame 提供了很多优点,尤其是当您尝试执行多个或嵌套超时,或者有一个更大的 JS 应用程序需要超时工作时.

回答by Elliot Bonneville

It is impossible to directly pause a Javascript function within a forloop then later resume at that point.

不可能在for循环中直接暂停 Javascript 函数然后在该点恢复。

回答by Sean Novak

I am executing a function where I need access to the outside object properties. So, the closure in Guffasolution doesn't work for me. I found a variation of nicosantangelosolution by simply wrapping the setTimeout in an if statement so it doesn't run forever.

我正在执行一个需要访问外部对象属性的函数。因此,Guffa解决方案中的闭包对我不起作用。我发现了nicosantangelo解决方案的变体,只需将 setTimeout 包装在 if 语句中,这样它就不会永远运行。

    var i = 0;
    function test(){

        rootObj.arrayOfObj[i].someFunction();
        i++;
        if( i < rootObj.arrayOfObj.length ){
            setTimeout(test, 50 ); //50ms delay
        }

    }
    test();

回答by BaSsGaz

The way I found was to simply use setInterval()to loop instead. Here's my code example :

我发现的方法是简单地使用setInterval()循环来代替。这是我的代码示例:

var i = 0;
var inte = setInterval(() => {
    doSomething();

    if (i == 9) clearInterval(inte);
    i++;
}, 1000);

function doSomething() {
    console.log(i);
};

This loops from 0 to 9 waiting 1 second in between each iteration.

这从 0 到 9 循环,在每次迭代之间等待 1 秒。

Output :

输出 :

0 1 2 3 4 5 6 7 8 9

回答by Ben Bieler

It is not possible to pausea loop. However you can delaythe execution of code fragments with the setTimeout() function. It would not make a lot of sense to pause the entire execution anyway.

无法暂停循环。但是,您可以使用 setTimeout() 函数延迟代码片段的执行。无论如何暂停整个执行没有多大意义。