jsfor循环终止,JS:for循环与暂停

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

}

};

解决方案

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

console.log(arr[i]);

if(arr[i]==pauseOn){

currentIndex = i+1;

setTimeout(loop,pauseTime);

return;

}

}

}

loop();

}

iterateArray(arr,3000,2);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值