2015-04-08 85 views
1

如何讓程序在clearInterval()函數後繼續計數,當我單擊「繼續」按鈕時。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
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