在clearInterval()之后继续计数

时间:2015-04-08 09:20:45

标签: javascript

如何在clearInterval()函数之后让程序继续计数,当我点击"继续"按钮。

 var num = 1;
 var count = 
      setInterval(
           function(){
                document.getElementById("myID").innerHTML = num;
           num++;
      },1000    
 );

 function pause(){
      clearInterval(count);
 }

 function continueCounting(){
      //????
 }

HTML:

 <body>
      <p id="myID"></p>
      <button onclick="pause()">Pause</button>
      <button onclick="continueCounting()">Continue</button>
 </body>

1 个答案:

答案 0 :(得分:1)

var num = 1;

// make count global
var count;

// put your counter in its own function
function doCount() {
  count = setInterval(
    function () {
      document.getElementById("myID").innerHTML = num;
      num++;
    }, 1000);
};

// run the function for the first time
doCount();

function pause() {
  clearInterval(count);
}

function continueCounting() {

  // run the function again starting the counter
  // from where it left off
  doCount();
}

DEMO