如何在 javascript 中实现无限循环 [英] how do an infinite loop in javascript
问题描述
我正在尝试使用 0 到 100 和 100 到 0 之间的 while 进行无限循环,但是浏览器崩溃了.有没有办法清除浏览器内存?这是我的代码:
Im trying to do an infinite loop using while between 0 to 100 and 100 to 0, but the browser crashes. There is a way to clear the browser memory? This is my code:
var a = 0;
var flag = true;
while (true) {
if (a < 100 && flag == true) {
a++;
} else {
a = 0;
flag = false;
if (a < 0) {
flag = true;
}
}
console.log(a);
}
推荐答案
无限 while 循环会阻塞主线程,相当于崩溃.你可以使用自调用函数(这让主线程在中间做一些其他的事情):
An infinite while loop will block the main thread wich is equivalent to a crash. You could use a selfcalling function ( wich leaves the main thread doing some other stuff inbetween):
(function main(counter){
console.log(counter);
setTimeout(main,0,counter+1);
})(0);
您可以将一个从 0 到 100 的循环,以及一个从 100 到 0 的循环放入其中,而不会过多地阻塞浏览器:
You can put a loop that goes from 0 to 100, and one that goes from 100 to 0 into it, without blocking the browser too much:
(function main(){
for(var counter=0;counter<100;counter++){
console.log(counter);
}
console.log(100);
while(counter){
console.log(--counter);
}
setTimeout(main,0);
})();
http://jsbin.com/vusibanuki/edit?console
进一步研究:JS IIFEs、函数表达式、非阻塞槽 setTimeout ...
Further research: JS IIFEs , function expression, non-blocking trough setTimeout ...
这篇关于如何在 javascript 中实现无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!