How timers work in JavaScript.
In this article, we'll take a closer look at how timers work in JavaScript.
As you know, JavaScript is an asynchronous, single-threaded programming language. This means that there is only one call stack, and code executes sequentially within that call stack. Synchronous means that the code is executed one at a time, and single-threaded means that there is only one main thread, which is the call stack.
However, asynchronous functionality can also be achieved. Timers are used to execute tasks after a specified time interval. Basically, you can use timers in JavaScript to delay code execution. Asynchronous functionality can also be achieved using JavaScript's timer functionality. Suppose you used a timer function to delay the execution of a function.
That function will not be executed when the JavaScript engine finds it. It will be stored somewhere else and the function will be executed when the timer expires. JavaScript provides two functions to delay task execution.
These are timer functions.
1. Set Timer function
Display a Text Once After 3 Second
// program to display a text using setTimeout method
function greet() {
console.log('Hello world');
}
setTimeout(greet, 3000);
console.log('This message is shown first');
Output
This message is shown first
Hello world
In the above program, the setTimeout()
method calls the greet()
function after 3000 milliseconds (3 second).
Hence, the program displays the text Hello world only once after 3 seconds.
The setTimeout()
method returns the interval id. For example
// program to display a text using setTimeout method
function greet() {
console.log('Hello world');
}
let intervalId = setTimeout(greet, 3000);
console.log('Id: ' + intervalId);
Output
Id: 3 Hello world
Post a Comment