how do an infinite loop in javascript

你离开我真会死。 提交于 2021-02-05 12:35:35

问题


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

}

回答1:


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

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

Further research: JS IIFEs , function expression, non-blocking trough setTimeout ...




回答2:


There is a way to clear the browser memory?

Yes. Virtually all browsers have a little icon somewhere that looks very similar to this:

This is called the "refresh". If you use this it will "clear the browser memory".




回答3:


You just need an infinite loop? If so just do

for(var i = 0; i < 1;){
  console.log('infinite');
};

if you need with a while

var = 0;
while(var < 1){
  console.log('looOOoOOoOoOp');
};


来源:https://stackoverflow.com/questions/43922400/how-do-an-infinite-loop-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!