【JavaScript】How to Use setInterval with Examples

Post in English

Introduction

 

Since I am currently working on creating an interval timer, I would like to explain how to use the JavaScript function setInterval.

 

What is the setInterval Function?

 

setInterval is a function used to execute a task repeatedly at a fixed time interval.

 

By combining it with the similar setTimeout() function, you can achieve more effective time control.
I have previously summarized how to use the setTimeout function.

 

How to use setTimeout method in JavaScript??

 

The syntax for using setInterval is as follows:

 

setInterval(function, interval in milliseconds);

 

It can also be written with window.setInterval, but in JavaScript, you can omit window, so the following syntax is also valid:

 

setInterval(function, interval in milliseconds);

 

For example, consider the following code:

 

let timer;

 

function Time() { window.alert('Hey'); }

 

timer = setInterval(Time, 3000);

 

Basic Usage of setInterval()

 

Let’s write a simple piece of code:

 

javascriptCopyEditsetInterval(() => console.log('Hello'), 3000);

 

In this code, the message “Hello” is displayed in the console every 3 seconds (3000 milliseconds).
By inserting an appropriate function inside setInterval, you can execute a function repeatedly at a fixed time interval.