JS:for循环与暂停 [英] JS: for loop with pauses

查看:964
本文介绍了JS:for循环与暂停的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何满足某些条件时,可以暂停循环?在下面的例子中,循环只是一次显示所有的值,而我希望它在任何时候停止它的具体值(例如2):

How can I make a loop pause when a certain condition is satisfied? In the example below loop just shows all values at once while I want it to stop any time it gets across specific value (e.g. 2):

a = [1,1,1,2,1,1,1,3,4,2,1]
for (var i = 0; i < a.length; i++) {
    if(a[i] == 2){
        setTimeout(console.log(a[i]), 1000)
    }else{
        console.log(a[i]);
    }
};


推荐答案

数组,暂停的时间(以毫秒为单位)以及暂停的时间。在函数内部,它将创建一个私有函数,用于遍历数组。如果pauseOn值被触发,setTimeout被用于在指定的pauseTime之后调用循环函数。

The below creates a function that takes 3 arguments, an array, the amount of time to pause (in milliseconds), and what to pause on. Inside the function it will create a private function that will be used to loop over the array. If the pauseOn value is encoutered a setTimeout is used to recall the loop function after the specified pauseTime

var arr = [1,1,1,2,1,1,1,3,4,2,1];

function iterateArray(arr,pauseTime,pauseOn){
   var currentIndex=0;

   function loop(){    
      for(i=currentIndex;i<arr.length; i++){
         console.log(arr[i]);
         if(arr[i]==pauseOn){
            currentIndex = i+1;
            setTimeout(loop,pauseTime);
            return;
         }
      }
   }
   loop();
}
iterateArray(arr,3000,2);

这篇关于JS:for循环与暂停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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