how do an infinite loop in javascript

前端 未结 3 435
再見小時候
再見小時候 2021-01-29 16:33

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:



        
相关标签:
3条回答
  • 2021-01-29 16:41

    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".

    0 讨论(0)
  • 2021-01-29 16:50

    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 ...

    0 讨论(0)
  • 2021-01-29 16:51

    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');
    };
    
    0 讨论(0)
提交回复
热议问题