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 pause and play a loop using event listeners in JavaScript?
In this article, we'll learn how to pause and resume a JavaScript loop using event listeners and promises. This technique is useful for creating controllable animations, counters, or any iterative process that needs user interaction.
An event listener attaches an event handler to an element, allowing us to respond to user interactions like button clicks.
Syntax
element.addEventListener(event, function, useCapture);
Parameters
event ? The name of the event (e.g., "click")
function ? The function to execute when the event occurs
useCapture ? Optional boolean, defaults to false
How It Works
We'll combine event listeners with promises to create a pausable loop:
A
govariable tracks the loop state (0 = running, 1 = paused)When paused, the loop waits for a promise that resolves when "Play" is clicked
Button states are managed using
setAttributeandremoveAttribute
Example
<!DOCTYPE html>
<html>
<body>
<h3>Pause and Play a Loop using Event Listeners</h3>
<p>Click buttons to control the counter</p>
<button id="start">Play</button>
<button id="stop">Pause</button>
<div>
<p id="counter">0</p>
</div>
<script>
// Initially disable start button
document.getElementById("start").setAttribute("disabled", "true");
var go = 0; // 0 = running, 1 = paused
// Helper function to create delays
function waitforme(ms) {
return new Promise(resolve => {
setTimeout(() => { resolve('') }, ms);
});
}
// Promise that resolves when play button is clicked
function waitForPlay() {
return new Promise(resolve => {
let playButtonClick = function () {
// Enable pause, disable play
document.getElementById("stop").removeAttribute("disabled");
document.getElementById("start").setAttribute("disabled", "true");
// Remove this event listener to prevent multiple triggers
document.getElementById("start").removeEventListener("click", playButtonClick);
go = 0; // Resume loop
resolve("resumed");
}
document.getElementById("start").addEventListener("click", playButtonClick);
});
}
// Pause button event listener
document.getElementById("stop").addEventListener("click", function () {
go = 1; // Pause loop
document.getElementById("stop").setAttribute("disabled", "true");
document.getElementById("start").removeAttribute("disabled");
});
// Main loop function
async function runCounter() {
for (let i = 0; i < 100; i++) {
document.getElementById("counter").innerHTML = i;
await waitforme(1000); // Wait 1 second
// If paused, wait for play button
if (go == 1) await waitForPlay();
}
}
runCounter();
</script>
</body>
</html>
Output
The counter starts at 0 and increments every second. Clicking "Pause" stops the counter, and clicking "Play" resumes it from where it left off.
Key Points
The
waitforme()function uses milliseconds (1000 = 1 second)Button states prevent multiple event listeners from being added
The loop continues from its current position when resumed
You can adjust the speed by changing the delay value
Conclusion
This approach combines promises with event listeners to create interactive, pausable loops. It's perfect for building controllable timers, animations, or step-by-step processes that users can manage.
