To perform actions at regular intervals, the Window object provides timer functions. There are two types of timers: some run only once, while others run continuously after a period of time.
setTimeout – one-time execution of actions after a period of time
Takes 2 parameters:
var timerId = setTimeout(someFunction, period)
The period parameter indicates the interval over which the function from the someFunction parameter will be executed.
And as a result, the function returns the id of the timer.
function writeText() { document.write("write text"); } setTimeout(writeText, 2000);
In this case, 2 seconds after the page is loaded, the writeText function will fire. The clearTimeout() function is used to stop the timer:
function writeText() { document.write("write text"); } var timerId = setTimeout(writeText, 10000); clearTimeout(timerId);
setInterval – constantly executes a certain function after a period of time
function updateTime() { console.log(new Date().toTimeString()); } setInterval(updateTime, 1000);
Here, every second (1000 milliseconds) the updateTime() function is called.
clearInterval() function works similar to function learTimeout(timerId).
requestAnimationFrame – timer for animation
The requestAnimationFrame() method works similarly to setInterval() except that it is more focused on animations and graphics and has a number of optimizations that improve its performance.
<head> <meta charset="utf-8" /> <style> #rect { margin: 100px; width: 100px; height: 100px; background: #50c878; } </style> </head> <body> <div id="rect"></div> <script> var square = document.getElementById("rect"); var angle = 0; function rotate() { angle = (angle + 2)%360; square.style.transform = "rotate(" + angle + "deg)"; window.requestAnimationFrame(rotate); } var id = window.requestAnimationFrame(rotate); </script> </body>
As a return result, the window.requestAnimationFrame() method returns a unique id, which can then be used to stop the animation:
window.cancelAnimationFrame(id);