DEV Community

Karthikeyan P
Karthikeyan P

Posted on

Explain requestAnimationFrame Like I'm Five

Top comments (1)

Collapse
 
nestedsoftware profile image
Nested Software • Edited

In the spirit of eli5, imagine that drawing a frame is like a kid asking their parent for something. The parent is busy, let's say preparing dinner in the kitchen, so the kid can't distract the parent too much, or else the food will burn. The kid just says "Dad, can you come and help me when you have a second?" When the parent is ready to do so, he comes over and helps a bit, and then goes back to cooking. If the kid needs more help, they can then ask the same question again. And so on.

A bit more detail: Normally your js code is processed in a single thread. When it's js that's running in the browser, that means a function that hogs the cpu can cause the whole page to hang. That is why you don't want to take control and start drawing whenever you want to. Instead you tell the event loop that you would like to draw a frame and give it a callback to execute when it thinks it's okay to do some drawing. You do a small amount of work at that time to draw a single frame - remember you don't want to hog the cpu too much. Then you can request another animation frame will which in turn get scheduled by the event loop, and so on.