In Javascript, we can use the "setTimeout" and "setInterval" functions to implement timers for delayed execution or repeated execution, respectively.
The timer functions allow us to execute code at specified intervals using timers.
There are two primary timer functions in Javascript.
setTimeout()
setInterval()
The "setTimeout" function is used to execute a function or code snippet after a specified delay.
function delayedFunction() { console.log("This will be executed after 2000 milliseconds (2 seconds)."); } // Set a timer for delayed execution setTimeout(delayedFunction, 2000);
function recurringFunction() { console.log("This will be executed every 1000 milliseconds (1 second)."); } // Set a timer for repeated execution let intervalId = setInterval(recurringFunction, 1000); // Clear the interval after a certain number of repetitions setTimeout(() => { clearInterval(intervalId); console.log("Interval cleared after 5000 milliseconds (5 seconds)."); }, 5000);
The setInterval function is used to repeatedly execute a function or code snippet at a specified interval.
Note: `setInterval` is used to execute `recurringFunction` every second, and `clearInterval` is used after 5 seconds to stop the repeated execution.
Both `setTimeout` and `setInterval` return a unique identifier (an integer) that we can use later to clear or cancel the timer using `clearTimeout` or `clearInterval`, respectively.
// setTimeout function is used to clearTimeout using it `numId` let timeoutId = setTimeout(() => { console.log("This won't be executed."); }, 2000); // Clear the timeout before it executes clearTimeout(timeoutId);
// setInterval function is used to clearInterval using its `numId` let timeIntervalId = setInterval(() => { console.log("This won't be executed."); }, 2000); // Clear the interval before it executes clearInterval(timeIntervalId);
We can cancel a timer before it executes (in the case of "setTimeout") or stop using `clearTimeout`:
We can cancel a timer before it executes (in the case of "setInterval") or stop using `clearInterval`:
`setTimeout` and `setInterval` are not guaranteed to be precise.
The specified time is a minimum delay, and the actual execution may be delayed due to other tasks in the Javascript runtime.