Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

setTimeout vs requestAnimationFrame

// setTimeout:
// 	Calls a function or evaluates an expression after a specified number of milliseconds.
// 	Doesn't mean that the function will be called after the exactly specified interval.
//	Can cause a browser to miss the frame.
// requestAnimationFrame
//	Works similarly to setTimeout 
//	called right before the next repaint in the browser occurs.

const timestamp = setTimeout(() => {...}); // runs as frequently as possible
const requestId = requestAnimationFrame(() => {...}); // runs once per frame

clearTimeout(timestamp); // clear previously added timeout
cancelAnimationFrame(requestId); // cancel an animation frame request 
 
PREVIOUS NEXT
Tagged: #setTimeout #requestAnimationFrame
ADD COMMENT
Topic
Name
3+3 =