how do an infinite loop in javascript

前端 未结 3 476
再見小時候
再見小時候 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: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 ...

提交回复
热议问题