How to start and stop/pause setInterval?

后端 未结 6 835
野性不改
野性不改 2020-12-05 02:59

I\'m trying to pause and then play a setInterval loop.

After I have stopped the loop, the \"start\" button in my attempt doesn\'t seem to work :

6条回答
  •  星月不相逢
    2020-12-05 03:35

    As you've tagged this jQuery ...

    First, put IDs on your input buttons and remove the inline handlers:

    
    
    
    

    Then keep all of your state and functions encapsulated in a closure:

    EDIT updated for a cleaner implementation, that also addresses @Esailija's concerns about use of 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
    });
    

    This ensures that none of your variables leak into global scope, and can't be modified from outside.

    (Updated) working demo at http://jsfiddle.net/alnitak/Q6RhG/

提交回复
热议问题