How to start and stop/pause setInterval?

后端 未结 6 832
野性不改
野性不改 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:25

    The reason you're seeing this specific problem:

    JSFiddle wraps your code in a function, so start() is not defined in the global scope.

    enter image description here


    Moral of the story: don't use inline event bindings. Use addEventListener/attachEvent.


    Other notes:

    Please don't pass strings to setTimeout and setInterval. It's eval in disguise.

    Use a function instead, and get cozy with var and white space:

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

提交回复
热议问题