简体   繁体   中英

Stuck with SetInterval ,SetTimeOut and Requestanimationframe

I'm kind of stuck with javascript timers. I have been reading the usage of setInterval ,setTimeOut are bad they cause page reflows and repaints,instead use request animation frame

I'm stuck and could not find one resource with a good explanation of how we can do that

I want to know ,how can we replace setinterval with requestanimationframe and settimeout with requestanimationframe

 var x = 0; function SayHi() { console.log("hi"); console.log(x); ++x if (x >= 10) clearInterval(intervalid); } var intervalid = setInterval(SayHi, 10); 

How can we replace the above code with requestanimationframe and how can we clear it

 function greetings(){ console.log("greetings to u"); } setTimeout(greetings,10); 

How can we replace setimeout in the above code with requestanimationframe.

If someone can explain the difference it would be of great help

Thanks

  • setTimeout() does something once after a period of time.
  • setInterval() repeatedly does something after each period of time.
  • requestAnimationFrame() does something once when the browser is "ready" (to repaint).

How are they the same?

You can see they all want to do something for you.

How are they different?

The basic differences are when and how often your something gets done. setInterval() is like setTimeout() called repeatedly. On the other hand, requestAnimationFrame() is like setTimeout() but called when the system is ready rather than after a (pseudo) fixed time.

How can requestAnimationFrame() replace setTimeout() ?

function greetings(timestamp) {
    console.log("greetings to u");
}
requestAnimationFrame(greetings);

How can requestAnimationFrame() replace setInterval() ?

var x = 0;
function SayHi(timestamp) {
    console.log(++x);
    if (x < 10) {
        window.requestAnimationFrame(SayHi);
    }
}
window.requestAnimationFrame(SayHi);

These are super simple examples based on your example code but I hope it gives you a sense of things.

You can also check out: Mozilla docs on requestAnimationFrame()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM