开始&使用javascript,jQuery停止/暂停setInterval

时间:2011-12-16 19:19:20

标签: javascript jquery loops setinterval

我正试图暂停,然后播放setInterval循环。

我停止循环后,my attempt中的“开始”按钮似乎不起作用:

HTML:

<input type="number" id="input" />
<input type="button" onclick="clearInterval(add)" value="stop"/>
<input type="button" onclick="start()" value="start"/>

JS:

input = document.getElementById("input");
function start() {
    add = setInterval("input.value++",1000);
}start();

有更好的/有效的方法吗?你可以自由使用jQuery。

谢谢!

7 个答案:

答案 0 :(得分:32)

请参阅jsFiddle上的工作演示: http://jsfiddle.net/qHL8Z/3/

<强> HTML

<input type="number" id="input" />
<input id="stop" type="button" value="stop"/>
<input id="start" type="button" value="start"/>

<强>的Javascript

$(function() {
    var timer = null, 
        interval = 1000,
        value = 0;

    $("#start").click(function() {
      if (timer !== null) return;
      timer = setInterval(function () {
          $("#input").val(++value);
      }, interval); 
    });

    $("#stop").click(function() {
      clearInterval(timer);
      timer = null
    });
});

答案 1 :(得分:17)

您遇到此特定问题的原因:

jsFiddle将您的代码包装在一个函数中,因此 start()未在全局范围内定义

enter image description here


故事的道德:不要使用内联事件绑定。使用addEventListener / attachEvent


其他说明:

不要将字符串传递给setTimeoutsetInterval。这是伪装的eval

改为使用函数,并使用var和空格:

var input = document.getElementById("input"),
    add;

function start() {
    add = setInterval(function () {
        input.value++;
    }, 1000);
}

start();

答案 2 :(得分:9)

正如你标记了这个jQuery ......

首先,在输入按钮上添加ID并删除内联处理程序:

<input type="number" id="input" />
<input type="button" id="stop" value="stop"/>
<input type="button" id="start" value="start"/>

然后将所有状态和函数封装在闭包中:

为更清洁的实施更新了

EDIT ,这也解决了@ Esailija对使用setInterval()的担忧。

$(function() {
    var timer = null;
    var input = document.getElementById('input');

    function tick() {
        ++input.value;
        start();        // restart the timer
    };

    function start() {  // use a one-off timer
        timer = setTimeout(tick, 1000);
    };

    function stop() {
        clearTimeout(timer);
    };

    $('#start').bind("click", start); // use .on in jQuery 1.7+
    $('#stop').bind("click", stop);

    start();  // if you want it to auto-start
});

这可确保您的所有变量都不会泄漏到全局范围内,也无法从外部修改。

(更新)http://jsfiddle.net/alnitak/Q6RhG/

的工作演示

答案 3 :(得分:3)

add是局部变量而不是全局变量试试这个

var add;
var input = document.getElementById("input");
function start() {
    add = setInterval("input.value++",1000);
}start();

答案 4 :(得分:1)

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

答案 5 :(得分:0)

我以这种方式使用多个计时器。这不是一个优雅的解决方案,但效果很好。

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

答案 6 :(得分:-4)

您无法在执行中停止计时器功能。您只能在完成后捕获它并防止它再次触发。

相关问题