JavaScript setTimeout is a method that allows you to call a function after a certain period of time, expressed in milliseconds.
The syntax of this method is: setTimeout(function, milliseconds, p1, p2, …).
Both milliseconds and p1 and p2 are optional parameters.
The mandatory function will be executed after the time indicated in milliseconds has elapsed, otherwise after 0 seconds, if this parameter is not specified. Therefore 0 is the default value.
JavaScript is not multi-threaded but single-threaded, meaning it can only execute one task at a time at any given time.
The JavaScript engine then executes the code from top to bottom, therefore it is said to be synchronous. Through callbacks, promises and methods such as setTimeout, JavaScript performs asynchronous activities.
In addition to the JavaScript engine, the web browser also has Event Loops, Call Stacks and Web API as components.
When we use setTimeout, the JavaScript engine inserts the execution context it creates into the Call Stack. This creates a timer in the Web API component of our web browser. When time elapses, the callback function, passed as an argument to the setTimeout method, is placed in a queue.
The event loop checks both the stack and the queue, removes the callback function from the queue, puts it on the stack and then the function is executed.
JavaScript setTimeout – first example
We realize two functions quote and other quote.
The first is a function that contains the setTimeout method which has as its first parameter a callback function that simply activates an alert with a famous quote from the movie “The Imitation Game“. The second parameter instead represents the time in milliseconds. Then the function, when called, will start after 2 seconds.
The second function, on the other hand, is a function that contains another alert with another quote, different from the previous one and which has no time limit.
Here, then, is the complete code for using the setTimeout method in JavaScript:
quote();
otherQuote();
function quote() {
// start after 2 seconds
setTimeout (function () {
alert('They are the people that no one imagines that they can do certain things those who do things that no one can imagine!');
}, 2000);
}
function otherQuote() {
alert('People never say what they mean, they always say something else. Yet they expect you to understand them ...');
}
Even if the quote function is called first, the otherCitation function will start first as it has no time restrictions.
setTimeout JavaScript and clearTimeout
Let’s create a simple count that we will stop with the clearTimeout method.
Then, let’s prepare our HTML page with this simple code:
<div id="container">Inizio conteggio:
<span id="conta"></span>
<button id="stop" class="btn">stop</button>
</div>
So I use a span where I’m going to put the progressive numbers and a button to stop everything.
Then I program my algorithm in JavaScript.
We initialize the count variable to 0 and save the timer created in a variable named myTimer.
Inside the callback function we will increment the count variable and then recursively call the setTimeout method to produce the next increments. Let’s give the time of 1 second.
When we click the stop button we call the stopCount function which will call the clearTimeout method on the myTimer variable.
Here is the complete code that uses the JavaScript setTimeout and clearTimeout methods:
var count = 0;
var myTimer = setTimeout(function timer() {
document.getElementById("count").innerHTML = ++count;
myTimer = setTimeout(timer, 1000);
}, 1000);
var stop = document.getElementById('stop');
stop.addEventListener('click',function (){
stopCount();
});
function stopCount() {
clearTimeout(myTimer );
}
Conclusion
In this lesson we speak about setTimeout and clearTimeout in JavaScript, in the next lesson we will talk about timers again using the setInterval method.
Some useful links
Introduction to JavaScript language
Learn JavaScript – basic concepts