requestAnimationFrame() not for animation — a key tool illustrated and explained

Marian Čaikovski
Geek Culture
Published in
5 min readAug 30, 2021

--

Test your understanding if you are an expert

The nice image is borrowed from http://clipart-library.com/clipart/453662.htm

requestAnimationFrame() is used to instruct the browser to execute a callback immediately before repainting the DOM. The method ensures that any changes introduced into the DOM by its callback are displayed in the next frame.

Animation, it is not the only or main purpose of requestAnimationFrame(). The name of this method is rather misleading. requestAnimationFrame() is also indispensable for rendering sophisticated user interfaces without wasting time on forced layouts.

Below I use minimal code samples to explain in detail the method works. While reading them, you can test your understanding of the basics of web development. I guess only a young developer can answer the three basic questions below.

Simple question

Let me start from a simple question. Imagine a page containing a single div:

<div id="root"></div>

The page loads a script that keeps inserting the same string Timeout into the div:

// 1.js
function timeout() {
root.innerHTML='Timeout'
setTimeout(timeout);
}
timeout();

--

--

Marian Čaikovski
Geek Culture

Java, JavaScript and SQL developer. Interested in data collection and visualization.