javascript暂停功能的时间

时间:2016-02-08 23:27:39

标签: javascript

我只想在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;
    }

它看起来怎么样?

3 个答案:

答案 0 :(得分:0)

检查循环中的时间距离:

<console>:12: error: value be is not a member of events.MyEvents

答案 1 :(得分:0)

只需重置间隔迭代:

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

答案 2 :(得分:0)

以下情况如何?

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与按钮上的事件相关联即可。我根据a Petri Net model the process编写了代码(Chionglo,2016)。

参考

Chionglo,J。F.(2016)。回复&#34; JavaScript暂停功能的时间&#34;在Stack Overflow。可在http://www.aespen.ca/AEnswers/dHxRF1455594076.pdf处获得。