What is setTimeout?
The setTimeout is a built-in JavaScript function that allows to the schedule the execution of the function or code snippet after a specified delay in which is measured in the milliseconds. This function is commonly used for:
- Delaying the execution of the code
- Implementing simple animations
- Scheduling tasks to the run in the future
Syntax:
setTimeout(function, delay);
Example: This illustrates the execution of a function to log a message after a delay of 2 seconds.
setTimeout(function() {
console.log('Delayed function executed.');
}, 2000);
Output:
Delayed function executed.
SetTimeout VS RequestAnimationFrame
The setTimeout and requestAnimationFrame are functions that can be used to the execute code after a delay. However, they serve different purposes and are optimized for the different scenarios especially when it comes to the animations and performance.