Timing Event
Introduction
JavaScript allows execution of code at specified time intervals. These time intervals are called timing events.
Methods
The two key methods to use with JavaScript are:
1. setTimeout()
Executes a function, after waiting a specified number of milliseconds.
Example:
function doSomething() {
console.log("Hello World");
}
setTimeout(doSomething, 3000);
This will log "Hello World" to the console after 3 seconds (3000 milliseconds).
2. setInterval()
Same as setTimeout(), but repeats the execution of the function continuously.
Here is an example:
function printMessage() {
console.log("Hello World!");
}
setInterval(printMessage, 5000);
This will log "Hello World!" to the console every 5 seconds (5000 milliseconds).
You can stop the execution of the function by using the clearInterval method and passing it the interval ID returned by setInterval.
Example:
function printMessage() {
console.log("Hello World!");
}
let intervalId = setInterval(printMessage, 5000);
// Stop the interval after 10 seconds
setTimeout(() => {
clearInterval(intervalId);
}, 10000);
In this example, the printMessage function will run every 5 seconds, but the interval will be cleared after 10 seconds.
The setTimeout(), setInterval(), and clearInterval() are all available in both the browser and Node.js.
Conclusion
In this article, we learned about timing events in JavaScript. We learned about the setTimeout() and setInterval() methods and how to use them.