简体   繁体   中英

How would I create a pause button in Javascript?

All of my functions execute after I press a start button (button 0):

<button class="button" id= "start">Start</button>
<button class="button" id= "pause">Pause</button>
document.getElementsByTagName('button')[0].addEventListener('click', function() {
        step1();
        step2();
        step3();
        step4();
        step5();
        step6();
        step7();
        step8();
        step9();
        step10();
        step11();
        step12();
        step13();
        step14();
        
    })

A sample function uses setTimeOut()

function step1() {
        setTimeout(() =>{
            $("#arrow1").show();
            $("#box").text("1. Step 1");
            document.getElementById('box1').style.cssText = 'background-color: white';
            document.getElementById('box2').style.cssText = 'background-color: red'; 
        }, 1000)  
    }

Is it possible to pause in the middle with the click of the pause button? It would have to be able to play again after, possibly by clicking a separate play button.

Maybe something like this. I did not test so far.

let pause = false

document.getElementsByTagName('button')[1].addEventListener('click', function() {
  pause != pause
} ) 


let steps = [
        step1,
        step2,
        step3,
        step4,
        step5,
        step6,
        step7,
        step8,
        step9,
        step10,
        step11,
        step12,
        step13,
        step14
]

document.getElementsByTagName('button')[0].addEventListener('click', function() {
let i = 0;
while(i < steps.length) {
  if(!pause){
    steps[i]()
    ++i
  }else{
    //check whether pause is disabled after one sec
    setTimeout(() => {}, 1000)
  }
}
})


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM