JavaScript 暂停时间函数

javascript pause function for time

本文关键字:函数 时间 暂停 JavaScript      更新时间:2023-09-26

我只想以 1 秒的间隔永久运行函数,当我单击按钮时,我想暂停此功能 2 秒。

这是我的代码:

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;
    }

会是什么样子?

在循环中检查时间距离:

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

只需重置间隔迭代:

// 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>

下面怎么样?

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);
}

只需将函数 btnPress 与按钮上的事件相关联即可。我基于Petri Net模型编写了代码(Chionglo,2016)。

参考

Chionglo, J. F. (2016).在 Stack Overflow 中回复"JavaScript 暂停时间函数"。可在 http://www.aespen.ca/AEnswers/dHxRF1455594076.pdf。