我正在尝试暂停,然后播放一个setInterval
循环。
在我停止循环后,my attempt中的"start“按钮似乎不起作用:
input = document.getElementById("input");
function start() {
add = setInterval("input.value++", 1000);
}
start();
<input type="number" id="input" />
<input type="button" onclick="clearInterval(add)" value="stop" />
<input type="button" onclick="start()" value="start" />
有没有一种可行的方法来做到这一点?
发布于 2011-12-17 03:22:45
add是一个局部变量,不是全局变量,试试这个
var add;
var input = document.getElementById("input");
function start() {
add = setInterval("input.value++", 1000);
}
start();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="input" />
<input type="button" onclick="clearInterval(add)" value="stop" />
<input type="button" onclick="start()" value="start" />
发布于 2011-12-17 03:27:37
(function(){
var i = 0;
function stop(){
clearTimeout(i);
}
function start(){
i = setTimeout( timed, 1000 );
}
function timed(){
document.getElementById("input").value++;
start();
}
window.stop = stop;
window.start = start;
})()
发布于 2021-03-24 17:54:16
我以这种方式使用多个计时器。这不是一个优雅的解决方案,但它工作得很好。
var timerclass = function () {
this.initialTime = Date.now();
var t=this;
var Timer = setInterval(function(){t.checkTime();}, 1000); //start the timer (goes to function checkTime every 1000ms )
this.timerstart=false;
}; //end of constructor
timerclass.prototype.StartTheTimer = function(){
this.initialTime = Date.now(); //Time right now
this.timerstart=true;
};
timerclass.prototype.checkTime= function(){
if(this.timerstart==true)
{
var timeDifference = Date.now() - this.initialTime;
console.log("Time ms: "+timeDifference);
}
};
timerclass.prototype.StopTimer= function(){
this.timerstart=false;
};
module.exports = timerclass;
然后在你的主代码中:
var MyTimerSystem = require(__dirname+'/class.timerclass.js');
var MyFirstTimerObject = new MyTimerSystem(); //First Timer
var MySecondTimerObject = new MyTimerSystem(); //Second Timer
停止计时器:
MyFirstTimerObject.StopTimer(); //Stop First Timer
MySecondTimerObject.StopTimer(); //Stop Second Timer
再次从0ms重新启动计时器:
MyFirstTimerObject.StartTheTimer(); //Start or restart the First timer
MySecondTimerObject.StartTheTimer(); //Start or restart the Second timer
https://stackoverflow.com/questions/8539079
复制相似问题