When does requestAnimationFrame fire?

2019-08-16 03:21发布

问题:

It seems that requestAnimationFrame only works after first run of js code is done: https://jsfiddle.net/pn91zmpc/

    var n = 0;

    function sleep(ms) {
        var date = new Date();
        var curDate = null;
        do { curDate = new Date(); }
        while (curDate - date < ms);
    }

    function refresh() {
         var body = document.getElementsByTagName("body")[0];
       body.textContent = n;
    }

    n=0;
    window.requestAnimationFrame(refresh);
    n = n+1;
    sleep(2000);
    n = n+1;
    sleep(2000);
    n = n+1;

I expected to see a countdown. Instead, I only see the last result. What do I need to change to see a countdown?

回答1:

What do I need to change to see a countdown?

A lot. Never ever try to sleep in a synchronous way. This will block everything which is just bad. Instead, just use async / await, which "sleeps" in a non-blocking way:

 const sleep = ms => new Promise(res => setTimeout(res, ms));

 (async function() {
   for(let n = 0; n < 4; n++) {
     document.body.textContent = n;
     await sleep(1000);
   }
})();

When does requestAnimationFrame fire?

Somewhere in the event loop. But as you block the browser synchronously, it never enters the event loop, hence it doesnt change the output.

PS: requestAnimationFrame, requests one animation frame. To update the UI multiple times, you need to call it multiple times.