Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Change the Time Interval of setinterval() Method at RunTime using JavaScript ?
The setInterval() method is used to call a particular block of code repeatedly after a specific time interval. It accepts two parameters: the function to execute and the time interval in milliseconds. Sometimes you need to change this interval dynamically during runtime for irregular or variable timing patterns.
JavaScript provides two main approaches to change the time interval of setInterval() at runtime:
Using the clearInterval() method
Using the setTimeout() method
Let us understand both approaches with practical examples.
Using the clearInterval() Method
The clearInterval() method stops a previously executing setInterval() function. To change the interval, you clear the existing interval and create a new one with a different time value.
Syntax
clearInterval(intervalID);
Example
This example demonstrates changing the interval time by doubling it on each execution:
<html>
<body>
<h2>Change setInterval() Time at Runtime</h2>
<p>The interval doubles each time (500ms, 1000ms, 2000ms, etc.)</p>
<button onclick="start()">Start</button>
<button onclick="stop()">Stop</button>
<div id="result"></div>
<script>
let result = document.getElementById("result");
let interval;
let time = 500;
let count = 1;
function start() {
// Clear any existing interval
clearInterval(interval);
// Display current execution
result.innerHTML += `Execution ${count}: after ${time}ms<br>`;
count++;
// Double the time for next execution
time = time * 2;
// Set new interval with updated time
interval = setInterval(start, time);
}
function stop() {
clearInterval(interval);
result.innerHTML += "<strong>Stopped</strong><br>";
}
</script>
</body>
</html>
Using setTimeout() Method
The setTimeout() method executes code only once after a specified delay. Unlike setInterval(), it doesn't repeat automatically. By calling setTimeout() recursively, you can achieve variable intervals without needing clearInterval().
Syntax
setTimeout(function, delay);
Example
This approach uses setTimeout() recursively to create variable intervals:
<html>
<body>
<h2>Variable Intervals with setTimeout()</h2>
<p>Each timeout has a different interval (500ms, 1000ms, 2000ms, etc.)</p>
<button onclick="startTimeout()">Start</button>
<button onclick="stopTimeout()">Stop</button>
<div id="timeoutResult"></div>
<script>
let timeoutResult = document.getElementById("timeoutResult");
let timeoutID;
let timeoutDelay = 500;
let timeoutCount = 1;
let isRunning = false;
function startTimeout() {
if (!isRunning) {
isRunning = true;
runTimeout();
}
}
function runTimeout() {
if (!isRunning) return;
// Display current execution
timeoutResult.innerHTML += `Timeout ${timeoutCount}: after ${timeoutDelay}ms<br>`;
timeoutCount++;
// Double the delay for next execution
timeoutDelay = timeoutDelay * 2;
// Set next timeout with new delay
timeoutID = setTimeout(runTimeout, timeoutDelay);
}
function stopTimeout() {
isRunning = false;
clearTimeout(timeoutID);
timeoutResult.innerHTML += "<strong>Stopped</strong><br>";
}
</script>
</body>
</html>
Comparison
| Method | Cleanup Required | Complexity | Best For |
|---|---|---|---|
| clearInterval() + setInterval() | Yes - clearInterval() | Medium | True intervals that need stopping/starting |
| setTimeout() recursive | Minimal - clearTimeout() | Low | Variable delays, one-time executions |
Key Points
Always clear existing intervals before setting new ones to prevent memory leaks
setTimeout() approach is cleaner for variable intervals since each execution is independent
Store interval/timeout IDs in variables for proper cleanup
Use flags (like
isRunning) to control execution flow
Conclusion
Both methods effectively change setInterval() timing at runtime. Use clearInterval() + setInterval() for traditional intervals, or setTimeout() recursively for cleaner variable timing. The setTimeout() approach is generally preferred for dynamic intervals.
