Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptHow to Pause and Play a Loop in JavaScript using Event Listeners...

How to Pause and Play a Loop in JavaScript using Event Listeners ?

Given below is a JavaScript program for DOM manipulation which is basically about How to Pause and Play a loop in JavaScript using event listeners (not to be confused with delay). In this article, we are using JavaScript with HTML so we need a web browser i.e., Chrome (recommended) or Electron Application. Pausing and playing a loop is such a difficult task in almost every programming languages and there is no simple solution to pause a loop in between its execution and playing it again at the click of a button just like we do in video clips, but JavaScript Promise concept makes it easy to pause and play loop with event listeners of DOM elements. Here pausing and playing a loop doesn’t mean delaying a loop. If you are looking for delaying a loop in JavaScript then we have already created a separate article for it, Visit: https://www.geeksforgeeks.org/how-to-delay-a-loop-in-javascript-using-async-await-with-promise/

Approach:  Our approach in this program for pausing and playing a loop is same as delaying a loop using Promise, but instead of resolving the Promise after some specific duration, we will resolve Promise by event listeners. Here in the code we used a function named as Pauser which will pause the program execution inside the loop, and we used a variable stats which acts like a flag for pause. If the stats is 0 then pause flag is false and if stats is 1 then pause flag is true and then it will call the Pauser() and wait for event listener to get resolved.

Syntax:

// Function Definition Syntax
document.getElementById("pa")
    .addEventListener("click", function () {
        stats = 1;
    })

function pauser() {
    return new Promise(resolve => {
        let playbuttonclick = function () {
            document.getElementById("playbuttonelement")
                .removeEventListener("click", playbuttonclick);
            stats = 0;
            resolve("resolved");
        }
        document.getElementById("playbuttonelement")
            .addEventListener("click", playbuttonclick)
    })
}

// Function Caller Syntax
async anyfunction()  {
    for (let i = 0; i < 10000; i++) {

        // This statement will check for 
        // the stats value and if it is
        // equal to 1 then it will call
        // pauser() and the loop will 
        // get paused!
        if (stats == 1) await pauser();
    }
}

We have discussed the whole working of the code above, now here is the Complete Code, just copy and create a separate html file and run it!

Example : In this example, we will use the above-defined methods in an HTML file

HTML




<!DOCTYPE html>
<html>
 
<body>
    <button id="pl">Play</button>
    <button id="pa">Pause</button>
     
    <div style="display:flex;">
        <p id="min">0</p>
           
        <p id="sec">0</p>
           
        <p id="milisec">0</p>
    </div>
 
    <script>
        document.getElementById("pl")
            .setAttribute("disabled", "true")
        var stats = 0;
 
        function waitforme(ms) {
            return new Promise(resolve => {
                setTimeout(() => { resolve('') }, ms);
            })
        }
 
        function pauser() {
            return new Promise(resolve => {
                let playbuttonclick = function () {
                    document.getElementById("pa")
                        .removeAttribute("disabled")
 
                    document.getElementById("pl")
                        .setAttribute("disabled", "true")
 
                    document.getElementById("pl")
                        .removeEventListener("click",
                                    playbuttonclick);
 
                    stats = 0;
                    resolve("resolved");
                }
                document.getElementById("pl")
                    .addEventListener("click", playbuttonclick)
            })
        }
 
        document.getElementById("pa")
            .addEventListener("click", function () {
 
            stats = 1;
 
            document.getElementById("pa")
                .setAttribute("disabled", "true")
 
            document.getElementById("pl")
                .removeAttribute("disabled")
 
        })
 
        let second;
        async function go() {
            second = document.getElementById("sec");
 
            for (let a = 0; ; a = a + 100) {
                if (a == 1000) {
                    a = 0;
                    second.innerHTML =
                         Number(second.innerHTML) + 1;
 
                }
 
                if (second.innerHTML == 60) {
                    second.innerHTML = 0;
 
                    let minute = document
                        .getElementById("min");
 
                    minute.innerHTML =
                        Number(minute.innerHTML) + 1;
                }
 
                document.getElementById("milisec")
                            .innerHTML = a / 100;
                await waitforme(100);
                if (stats == 1) await pauser();
            }
        }
        go();
    </script>
</body>
 
</html>


Output:

Application of the above implementation: Stopwatch, pausing/playing any custom animation made in javascript, Data Visualization, etc.

Note: We had used ‘click’ event in this code, other users can use any event handler such as click, mousenter, mouseover, mouseon, mousemove, keypress, etc of his/her choice.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments