Languages
[Edit]
EN

JavaScript - setTimeout example

0 points
Created by:
Krzysiek
651

In this article, we would like to show you how to useĀ setTimeout in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

let x = 0;
const action = () => {
  console.log(x);
  if (++x < 3) {
    setTimeout(action, 1000);
  }
};
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.

1. Basic setTimeout example

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:

// ONLINE-RUNNER:browser;

let x = 0;
const action = () => {
  console.log(x);
  if (++x < 3) {
    setTimeout(action, 1000);
  }
};
setTimeout(action, 1000);

2. setTimeout with additional arguments example

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:

// ONLINE-RUNNER:browser;

const action = (arg1, arg2) => {
  console.log(arg1 + arg2);
};

console.log('setTimeout will display text in 3 seconds...');
setTimeout(action, 3000, 'Hello ', 'world!')

References

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
šŸš€
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ā¤ļøšŸ’» šŸ™‚

Join