setinterval()
Published Jun 13, 2023
Contribute to Docs
The setInterval()
method is used to execute a function repeatedly at specified time intervals.
Syntax
The setInterval()
function is used to execute a function repeatedly at a specified interval (delay).
intervalID = setInterval(function, delay, arg0, arg1, /* … ,*/ argN)
setInterval()
takes the following parameters:
- The
function
to be executed or, alternatively, a code snippet. - The
delay
in milliseconds between each execution. This parameter is optional and if not provided defaults to 0. - Optional additional arguments (
arg0
,arg1
…argN
), which are passed to thefunction
once the timer expires.
After setInterval()
is executed, the function
argument is executed only after the given delay
.
It returns a numeric, non-zero value as intervalID
of the timer created by the call to setInterval()
. This intervalID
value can be passed to clearInterval()
to cancel the interval.
Example
Following code outputs “Hello” 3 times to given number each second
let i = 1; // Initial countconst iMax = 3; // Max count// Function passed to `setInterval()` methodfunction sayHello() {console.log('Hello number ' + i);i = i + 1;if (i > iMax) {clearInterval(intervalID); // Canceling the repeating action of the `setInterval()` method}}const intervalID = setInterval(sayHello, 1000); // Calling the `setInterval()` method
Expected output:
Hello number 1Hello number 2Hello number 3
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours