JavaScript setInterval() Function Examples

Share this article

The JavaScript setInterval function can be used to automate a task using a regular time based trigger. Just to be clear, setInterval() is a native JavaScript function. This function is very similar to the jQuery setTimeout() Function.

Basic setInterval() Example

setInterval(function() {
      // Do something every 5 seconds
}, 5000);
Tips: If your changing images dynamically load variables from a PHP script you will need to add some sort of random number to the script so that it forces a refresh in all browsers. You can do this by using the following code to generate a random number.
$(document).ready(function()
{
    var refreshId = setInterval( function() 
    {
        var r = (-0.5)+(Math.random()*(1000.99));
        $('#img-container').load('images/gallery/best/random.php?'+r);
    }, 5000);
});
Tips:
You might also have to use the ajax method instead of load, to prevent the AJAX request to be cached. Tips: Alternatively, you could stick header(“Cache-Control: no-cache, must-revalidate”); towards the top of your random.php file to prevent the browser from caching.

Frequently Asked Questions (FAQs) about setInterval in JavaScript

What is the Difference Between setInterval and setTimeout in JavaScript?

Both setInterval and setTimeout are built-in JavaScript functions that execute code after a specified period of time. However, they work differently. setInterval executes the code repeatedly after every specified interval of time until it is stopped. On the other hand, setTimeout executes the code only once after the specified time delay.

How Can I Stop or Clear a setInterval in JavaScript?

To stop or clear a setInterval, you can use the clearInterval function. This function requires the ID value returned by the setInterval function as a parameter. Here’s an example:
let intervalID = setInterval(myFunction, 3000);
// To clear the interval
clearInterval(intervalID);
In this code, myFunction will stop executing every 3 seconds once clearInterval is called.

Can I Use setInterval with Arrow Functions?

Yes, you can use setInterval with arrow functions. Arrow functions provide a concise syntax to write function expressions in JavaScript. Here’s an example:
setInterval(() => {
console.log('Hello, World!');
}, 1000);
In this code, ‘Hello, World!’ will be logged to the console every second.

How Can I Use setInterval in a Class in JavaScript?

You can use setInterval in a class by referencing the class method with the ‘this’ keyword. However, you need to bind the ‘this’ keyword to the class instance, otherwise, it will refer to the global object. Here’s an example:
class MyClass {
constructor() {
this.myMethod = this.myMethod.bind(this);
setInterval(this.myMethod, 1000);
}

myMethod() {
console.log('Hello, World!');
}
}
In this code, ‘Hello, World!’ will be logged to the console every second.

Can I Pass Additional Parameters to the Function in setInterval?

Yes, you can pass additional parameters to the function in setInterval. After the delay parameter, you can add any number of parameters which will be passed to the function when it is invoked. Here’s an example:
setInterval(function(a, b) {
console.log(a + b);
}, 1000, 'Hello, ', 'World!');
In this code, ‘Hello, World!’ will be logged to the console every second.

How Can I Use setInterval with Promises in JavaScript?

You can use setInterval with Promises by wrapping the setInterval inside a Promise constructor. However, remember that setInterval will keep executing until it is stopped, so you need to provide a condition to resolve or reject the promise. Here’s an example:
let promise = new Promise((resolve, reject) => {
let count = 0;
let intervalID = setInterval(() => {
count++;
if (count > 5) {
clearInterval(intervalID);
resolve();
}
}, 1000);
});
In this code, the promise will be resolved after 6 seconds.

What Happens if the Function Execution Time is Longer Than the SetInterval Delay?

If the function execution time is longer than the setInterval delay, the next call will be queued and will execute immediately after the current one finishes. This could lead to function calls stacking up, which might cause performance issues.

Can I Use setInterval in Node.js?

Yes, you can use setInterval in Node.js. It works the same way as it does in the browser. Here’s an example:
setInterval(() => {
console.log('Hello, Node.js!');
}, 1000);
In this code, ‘Hello, Node.js!’ will be logged to the console every second.

How Can I Use setInterval with async/await in JavaScript?

You can use setInterval with async/await by wrapping the setInterval inside a Promise and then using the async/await syntax to handle the promise. Here’s an example:
async function myAsyncFunction() {
let promise = new Promise((resolve, reject) => {
let count = 0;
let intervalID = setInterval(() => {
count++;
if (count > 5) {
clearInterval(intervalID);
resolve();
}
}, 1000);
});

await promise;
console.log('Hello, async/await!');
}
In this code, ‘Hello, async/await!’ will be logged to the console after 6 seconds.

Can I Use setInterval with jQuery?

Yes, you can use setInterval with jQuery. You can use it to periodically update a part of the webpage, animate elements, or perform any other task. Here’s an example:
setInterval(() => {
$('#myElement').fadeOut(500).fadeIn(500);
}, 1000);
In this code, the element with the ID ‘myElement’ will fade out and then fade in every second.

Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQuerysetInterval example
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week