How to output to console in real time in Javascript?

后端 未结 5 921
南方客
南方客 2020-12-20 09:40

In Javascript, when you write a piece of code like the one below, it seems like the computer will first complete the entire loop 100 000 times (which can take a second or tw

5条回答
  •  攒了一身酷
    2020-12-20 10:19

    If you want a smoother output, I would suggest avoiding the for loop, and instead use requestAnimationFrame which will manage when to print out the results.

    var counter = 0;
    var max = 100000;
    function myPrint(){
        if(counter < max){
            console.log(counter++);
            requestAnimationFrame(myPrint);
        }
    }
    myPrint();
    

提交回复
热议问题