JS:for循环与暂停

编程入门 行业动态 更新时间:2024-10-24 21:29:47
本文介绍了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循环与暂停

本文发布于:2023-11-27 03:02:29,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!