2016-12-04 50 views
0

我想讓睡眠「定時器」功能,直到有人決定是否想要留下或離開我的網站後點擊「退出」按鈕,所以在後臺時間被凍結。但是如果他決定留下來,定時器功能應該繼續。我不知道該怎麼做。任何人都可以幫我嗎?感謝所有的建議。如何在確認框中決定睡眠功能

<!DOCTYPE html> 
<html> 
<body> 
<button onclick="exit();">exit</button> 
    <p id="seconds">30</p> 

    <script type="text/javascript"> 
     var clock; 



     function timer() { 
      clearInterval(clock); 
      var start = new Date().getTime(); 
      clock = setInterval(function() { 
       var seconds = Math.round(30 - (new Date().getTime() - start)/1000); 
       if (seconds >= 0) 
        document.getElementById('seconds').innerHTML = seconds; 
       else 
        clearInterval(clock); 



        if (seconds==0)  document.getElementById("fotka").innerHTML='<img src="mopsik.jpg"/>'; 




      }, 1000); 
     } 

     function exit(){ 

var result = confirm("Do you really want to leave this page?"); 
if (result == true) { 
window.location.href="www.something.com"; 
} 
else { 

} 
} 

     timer(); 
    </script> 
</body> 
</html> 
+0

'setInterval'每隔X次執行一次函數,您可以清除exit函數中的間隔,如果結果爲false,則再次運行該函數。 –

回答

0

正好當用戶點擊退出時,清除間隔(意味着他不會再計算秒數),如果結果爲false,則再次開始間隔。

var clock; 
var start; 

function StartTimer() { 
    if (clock) { 
    clearInterval(clock); 
    } 
    start = new Date().getTime(); 
    startInterval(); 
} 

function startInterval() { 

    clock = setInterval(function() { 
    var seconds = Math.round(30 - (new Date().getTime() - start)/1000); 

    if (seconds >= 0) { 
     document.getElementById('seconds').innerHTML = seconds; 
    } else{ 
     clearInterval(clock); 
    } 

    if (seconds==0) 
     document.getElementById("fotka").innerHTML='<img src="mopsik.jpg"/>'; 

    }, 1000); 

} 

function exit() { 

    clearInterval(clock); 
    var result = confirm("Do you really want to leave this page?"); 

    if (result == true) { 
    window.location.href="www.something.com"; 
    } else { 
    startInterval(); 
    } 
}