When does requestAnimationFrame fire?

落花浮王杯 提交于 2019-12-11 19:55:17

问题


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.



来源:https://stackoverflow.com/questions/50087233/when-does-requestanimationframe-fire

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