Nearby lessons

15 of 22

JavaScript: setInterval() Method

📌 What is setInterval()?

The setInterval() method repeatedly calls a function with a fixed time delay between each call, until it is cleared using clearInterval().

1️⃣ Basic Usage of setInterval()

This example shows how to print a message every 2 seconds.

Example02
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

2️⃣ Using Named Function with setInterval()

You can also pass a named function instead of an anonymous function.

Example03
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

3️⃣ Passing Arguments to the Function

You can pass additional arguments to the function being executed by setInterval().

Example04
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

4️⃣ Stopping setInterval() using clearInterval()

You can stop the interval by storing the ID and passing it to clearInterval().

Example05
🚀Code Cell
Loading Editor...
✏️ You can edit this code — click Run to refresh the preview.
Output

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3