![](/img/trans.png)
[英]How to stop executinf function after certain amount of time in JavaScript
[英]How can I stop a page from refreshing after a certain amount of time javascript
我希望頁面經常重新加載,但是如果某個用戶在5分鍾內處於非活動狀態,則希望停止重新加載頁面。 我在http://codepen.io/tetonhiker/pen/gLeRmw上有一個示例。
現在每10秒刷新一次。 同樣,我希望它在用戶不活動后刷新5分鍾后停止說。 我怎樣才能做到這一點?
var timer = null; $(function() { // Get the time to stop the effect var stopTime = new Date(); stopTime.setMinutes(stopTime.getMinutes() + 5); // Get a reference to the timer so it can be cancelled later timer = setInterval(function() { // Check to see if the timer should stop var currentTime = new Date(); if(currentTime < stopTime){ var randomnumber = Math.floor(Math.random() * 100); $('#show').text( 'I am getting refreshed every minute..! Random Number ==> ' + randomnumber); } else { // Stop the timer clearInterval(timer); } }, 60 * 1000); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="show" align="center"></div> <div align="center"> </div>
只需設置一個與計時器id相等的變量,並在滿足條件時取消:
var timer = null;
// As soon as the document is ready:
$(function() {
// Activate the timer:
startClock();
});
// And, when the user interacts with the page, start over
$(document).on("mousemove click", function(){
// Stop the previously running timer
clearInterval(timer);
// Start the clock over again:
startClock();
});
function startClock(){
// Get the time to stop the effect
var stopTime = new Date();
stopTime.setMinutes(stopTime.getMinutes() + 5);
// Get a reference to the timer so it can be cancelled later
timer = setInterval(function() {
// Check to see if the timer should stop
var currentTime = new Date();
if(currentTime < stopTime){
var randomnumber = Math.floor(Math.random() * 100);
$('#show').text("I am getting refreshed every 10 seconds..! " +
"Random Number ==> " + randomnumber);
} else {
// Stop the timer
clearInterval(timer);
}
}, 10000);
}
您可以通過幾種不同的方法來實現。 首先,我將假設您已經有邏輯來檢查一個人是否閑置了5分鍾(因為這使回答起來更容易了,:D)
您可以做的就是調用setInterval並將其結果存儲在變量中。 如果用戶閑置5分鍾,則使用window.clearInterval(thatVariable)結束循環。
否則,請更改您的邏輯以改為使用setTimeout,並讓它遞歸調用自身,只要用戶沒有閑置5分鍾即可。
<script type="text/javascript">
setTimeout(function () {
location.reload();
}, 60 * 1000);
</script>
setTimeout將在指定的毫秒數后重新加載頁面,因此60 * 1000 = 1m。 另外,由於頁面正在刷新,因此將始終在頁面加載時設置超時。
一種簡單的方法是將setInterval
與setTimeout
混合使用。
function refresh() {
var randomnumber = Math.floor(Math.random() * 100);
$('#show').text('I am getting refreshed every 10 seconds..! Random Number ==> ' + randomnumber);
}
var intervalId = setInterval(refresh, 10 * 1000);
setTimeout(function () {
clearInterval(intervalId);
alert('refresh stop!');
}, 5 * 60 * 1000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.