如何在一段时间javascript后停止刷新页面

时间:2016-12-06 18:18:01

标签: javascript jquery html

我希望我的页面每隔一段时间重新加载一次,但如果用户在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>

4 个答案:

答案 0 :(得分:3)

只需设置一个等于计时器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);
}

答案 1 :(得分:2)

您可以通过几种不同的方式实现这一目标。首先,我假设您已经存在逻辑,以检查一个人是否已经空闲了5分钟(因为这样可以更容易回答:D)

您可以做的是当您调用setInterval时,将其结果存储在变量中。此时如果用户空闲5分钟,则window.clearInterval(thatVariable)结束循环。

否则,将逻辑更改为使用setTimeout,并且只要用户没有空闲5分钟,就让它以递归方式调用自身。

答案 2 :(得分:0)

<script type="text/javascript">
    setTimeout(function () { 
      location.reload();
    }, 60 * 1000);
</script>

setTimeout将在指定的毫秒数后reload页面,因此60 * 1000 = 1m。此外,由于页面正在刷新,因此将始终在页面加载时设置超时。

答案 3 :(得分:0)

一种简单的方法是将setIntervalsetTimeout混合。

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);