Srisa Srisa - 1 year ago 85
HTML Question

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() {

if (x >= 10)

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");


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

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


Answer Source
  • 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 recursively while 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"); }

How can requestAnimationFrame() replace setInterval()?

var x = 0;
function SayHi(timestamp) {
  if (x < 10) { 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 and / or SO docs on requestAnimationFrame()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download