setTimeout and setInterval
To finish the section, let's quickly talk about timers in JavaScript. We have two kinds of timers in JavaScript. First, the setTimeout
timer, which runs just once, after a defined time, and the setInterval
timer, which keeps running forever until we stop it.
We can use set timeout to execute some code at some point in the future. Let's use this to simulate ordering a pizza. When ordering a pizza, it doesn't arrive right away. Instead, it's going to take some time. And we can simulate that.
Let's write that...
setTimeout()
The setTImeout
function receives a callback function just like some array methods or DOM event handlers.
setTimeout(() => {
console.log('Pizza is here! 🍕')
})
The above callback function is the first argument of the setTi meout
function. Again, we do not call the callback function ourselves. We simply pass the callback function as an argument to the setTimeout
function. And it is the setTimeout
function that will call the callback function for us in the future. And when does that future arrive? Well, that's what we specify as the second argument to the setTimeout
function.
The second argument is the time in milliseconds that we want to wait before the callback function is called. So, let's say we want to call our callback function after 5 seconds, we then have to pass 5000 as the second argument.
setTimeout(() => {
console.log('Pizza is here! 🍕')
}, 5000)
Now, if you run this code, you will notice that after 5 seconds the above text will be logged in your console. What's really important to realize here is that the setTimeout
function is not blocking. It does not block the execution of the code that comes after it. Let's assume we have the below code.
setTimeout(() => {
console.log('Pizza is here! 🍕'); // Executed after 5 seconds
}, 5000);
console.log('Ordering pizza...'); // Executed immediately
When the execution of our code reaches the setTimeout
function, it will not wait for 5 seconds. Instead, it will call the setTimeout
function, then it will register the callback function to be called later. And then the code execution simply continues. So, the console.log
statement will be executed immediately. And then after 5 seconds, the callback function will be called. This mechanism is called asynchronous JavaScript. And we will talk about how all of this works behind the scenes very soon.
Now what if we needed to pass some arguments to the callback function? It's not that simple because we are not calling the callback function ourselves. However, the setTimeout
function has a solution for that. That is, all the arguments that we pass after the delay time will be passed to the callback function. Let's see that in action.
const ingredients = ['olives', 'spinach'];
setTimeout(
(ing1, ing2) => {
console.log(`Here is your pizza with ${ing1} and ${ing2}`);
},
5000,
...ingredients
); // The order of the arguments is important 👈🏽
console.log('Ordering pizza...');
Another thing I want to show you about the setTimeout
function is that we can actually cancel the timer before it is executed. Let's see that in action.
const ingredients = ['olives', 'spinach'];
const pizzaTimer = setTimeout(
(ing1, ing2) => {
console.log(`Here is your pizza with ${ing1} and ${ing2}`);
},
5000,
...ingredients
);
if (ingredients.includes('spinach')) {
clearTimeout(pizzaTimer);}
console.log('Ordering pizza...');
Let's now talk about the setInterval
function. We learned that the setTimeout
function simple schedules a callback function to be called after a certain time. But the callback function is only called once. Now what is we wanted to call the function over and over again? Say every 5 seconds, 10 seconds, or 1 hour. Well, that's where the setInterval
function comes in.
Let's see that in action by building a simple clock that displays the current time every second in our console.
setInterval(() => {
const now = new Date();
console.log(now);
}, 1000);
Let's finish this lecture by building a really nice clock, that displays the hour, minutes and seconds using the stuff we've learned in the previous lectures.
const now = new Date();
const options = {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
};
const formattedClock = new Intl.DateTimeFormat(
navigator.language,
options
).format(now);
setInterval(() => {
console.log(formattedClock);
}, 1000);