JIrka ZAvadil February 2016

javascript pause function for time

I just want to run function forever in 1 sec. intervals and when I click on button I want to pause this function for 2seconds.

This is my code:

var check = 0;

    setInterval(loop,1000);

    function wait(){
    	document.write("waiting 2seconds");
    }

    function loop(){
    	if(check == 1){
    		setTimeout(wait,2000); // here at this point I want to pause function loop for 2seconds
    		check = 0;
    	}
    	document.write("doing something every 1sec")
    }

    function btnPress(){
    	check = 1;
    }

How would it look like?

Answers


stdob-- February 2016

Check time distance in loop:

function loop(){
    if(check > 0){
      check++;
    }
    if ( (check===0) || (check===3) {
       check = 0;
       document.write("doing something every 1sec");
    }
}


Vidul February 2016

Just reset the interval iteration:

// note that you cannot get guarantee that
// there will be no delay (a pause longer than 2 seconds) 

var pause = 1000, // in seconds
  dom = document.getElementById('this_button'),
  interval_id = interval(pause);

dom.onclick = function() {
  pause = 2000;
  
  clearInterval(interval_id);
  
  setTimeout(function() {
    loop();
    pause = 1000;
    interval_id = interval(pause);
  }, pause);
};

function interval(pause) {
  return setInterval(loop, pause);
}

function loop() {
  console.log("paused for", pause / 1000, "seconds at", new Date());
}
<button id="this_button">
  paused for 2 second
</button>


John Frederick Chionglo February 2016

How about the following?

var intervalObj;

function loop() {
  document.writeln(“Doing something every second.”);
}

intervalObj = setInterval(“loop()”, 1000);

function t3() {
  document.writeln(“ and 2 seconds is over.”);
  intervalObj = setInterval(“loop()”, 1000);
}

function btnPress() {
  document.write(“Starting to wait for 2 seconds …”);
  clearInterval(intervalObj);
  intervalObj = setTimeOut(“t3()”, 2000);
}

Just associate the function btnPress with an event on your button. I wrote the code based on a Petri Net model the process (Chionglo, 2016).

Reference

Chionglo, J. F. (2016). A Reply to "JavaScript pause function for time" at Stack Overflow. Available at http://www.aespen.ca/AEnswers/dHxRF1455594076.pdf.

Post Status

Asked in February 2016
Viewed 3,485 times
Voted 6
Answered 3 times

Search




Leave an answer