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.