Languages
[Edit]
EN

JavaScript - setInterval() function example

3 points
Created by:
p_agon
589

In this article, we would like to show you how to use setInterval() in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

setInterval(() => {
    console.log('This will be displayed every 1000ms (1s).');
}, 1000);

or:

// ONLINE-RUNNER:browser;

const handle = setInterval(() => {
    console.log('This will be displayed every 1000ms (1s).');
}, 1000);

clearInterval(handle);  // stops intervals

 

1. Documentation

Syntax

setInterval(callback)
setInterval(callback, delay)
setInterval(callback, delay, arg1, arg2, arg3, ...)

Parameterscallback - function called every indicated time (interval),
delay - optional interval time as an integer number (in milliseconds),
arg1, arg2, arg3, ... - optional arguments passed as callback arguments.
ResultCreated interval handle (as integer number).
Description

setInterval() function starts logic that calls callback function every indicated interval time.

setInterval() logic can be stopped by calling clearInterval() function with interval handle as an argument.

 

Below we present some practical examples for better understanding.

1. Simple setInterval example

In this example, we create and call a simple function that displays some text every second.

Runnable example:

// ONLINE-RUNNER:browser;

setInterval(() => {
    console.log('This will be displayed every 1000ms (1s).');
}, 1000);

2. Calling setInterval the specified amount of times

In this example, we create a function with setInterval that counts to 5 every second.

Runnable example:

// ONLINE-RUNNER:browser;

let i = 0;
let interval = setInterval(() => {
    console.log(i + 1);
    if (++i === 5) {
        clearInterval(interval);
    }
}, 1000);

3. Custom setInterval

In this example, we create customSetInterval that takes in three arguments:

  • count - how many times we want to call the callback function,
  • delay - time between callback function calls,
  • callback - a function to be called.

Runnable example:

// ONLINE-RUNNER:browser;

const customSetInterval = (count, delay, callback) => {
    var i = 0;
    var interval = setInterval(() => {
        callback(i, count);
        if (++i === count) {
            clearInterval(interval);
        }
    }, delay);
};


// Usage example:

const foo = (index, count) => console.log(`${index + 1}/${count} Some text here ...`);

customSetInterval(5, 1000, foo);

Alternative titles

  1. JavaScript - setInterval & clearInterval
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