EN
JavaScript - setTimeout example
0 points
In this article, we would like to show you how to use setTimeout
in JavaScript.
Quick solution:
xxxxxxxxxx
1
let x = 0;
2
const action = () => {
3
console.log(x);
4
if (++x < 3) {
5
setTimeout(action, 1000);
6
}
7
};
8
setTimeout(action, 1000);
setTimeout
is a method that sets a timer that executes a function or specified piece of code after the timer expires.
Basic version of setTimeout
takes in two arguments:
- a
function
(or piece of code) to be executed, delay
- time in milliseconds the timer should wait before the function or code passed in as a first argument is executed.
You can also pass additional arguments which will be passed through to the function
.
Note:
You can find more information about
setTimeout
and passing arguments to the method - here.
Below we create a function with setTimeout
inside that calls the function three times every 1 second.
Arguments passed:
- function:
action
, - delay:
1000
(1 second).
Runnable example:
xxxxxxxxxx
1
let x = 0;
2
const action = () => {
3
console.log(x);
4
if (++x < 3) {
5
setTimeout(action, 1000);
6
}
7
};
8
setTimeout(action, 1000);
Below we create a function that takes in two arguments which we will pass through the setTimeout
as additional arguments after function
and delay
.
Runnable example:
xxxxxxxxxx
1
const action = (arg1, arg2) => {
2
console.log(arg1 + arg2);
3
};
4
5
console.log('setTimeout will display text in 3 seconds...');
6
setTimeout(action, 3000, 'Hello ', 'world!')