如何在JavaScript中进行无限循环 [英] how do an infinite loop in javascript

查看:80
本文介绍了如何在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屋!

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