![](/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.