首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何启动和停止/暂停setInterval?

如何启动和停止/暂停setInterval?
EN

Stack Overflow用户
提问于 2011-12-17 03:19:20
回答 4查看 125.2K关注 0票数 29

我正在尝试暂停,然后播放一个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" />

有没有一种可行的方法来做到这一点?

EN

回答 4

Stack Overflow用户

发布于 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" />

票数 4
EN

Stack Overflow用户

发布于 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;
})()

http://jsfiddle.net/TE3Z2/

票数 2
EN

Stack Overflow用户

发布于 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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8539079

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档