2017-06-06 28 views
0

我在我的页面上有一个计时器10分钟。当时间超过页面应该刷新自己并删除会话值。window.location.reload不起作用

它工作得很好,但突然停止工作..计时器卡在0:01。

看起来像是当location.reload()执行后页面卡住了。资源管理器的状态栏不断显示加载图标..一遍又一遍。

我的代码如下:

<script> 
        var counter = setInterval(timer, 1000); 

        function timer() { 
         count = count - 1; 

         // if time exceed then refresh the page. 
         if (count <= 0) { 
          location.reload(); 
         } 
         else 
         { 
          var timerSpan = document.getElementById("timerCountdown"); 

          if (count <= timerTurnToRed) { 
           //Make Red 
           timerSpan.className = "finalCountdown"; 
          } 

          // Calculate remaining minutes & seconds 
          var remainingMinutes = Math.floor(count/60) 

          // Check if it is negative 
          if (remainingMinutes < 0) 
           location.reload(); 

          var remainingSecs = count - (remainingMinutes * 60); 
          if (remainingSecs < 10) { 
           remainingSecs = "0" + remainingSecs.toString(); 
          } 

          timerSpan.innerHTML = remainingMinutes + ":" + remainingSecs; 
         } 
        } 
       </script> 
+0

哪里是设置 “计数” 的代码?重新加载后可能为0。 –

+0

你没有提供你的问题的所有代码... –

+0

只是一个疯狂的猜测,但也许定时器不断重新加载。就像它做了'location.reload()'那么在完成重新加载新页面和清除旧页面之前,它会再次触发'location.reload()',从而导致它停止再次加载并重新开始。并结束。尝试停止一些检查的时间间隔,也许改变测试'if(count === 0)' –

回答

0

不要把它在哪里按预期工作的问题。 StackOverflow代码评估器将防止重新加载。

var count = 15; 
 
var timerTurnToRed = 10; 
 
var counter = setInterval(timer, 1000); 
 

 
        function timer() { 
 
         count--; 
 

 
         // if time exceed then refresh the page. 
 
         if (count <= 0) { 
 
          location.reload(); 
 
         } 
 
         else 
 
         { 
 
          var timerSpan = document.getElementById("timerCountdown"); 
 

 
          if (count <= timerTurnToRed) { 
 
           //Make Red 
 
           timerSpan.className = "finalCountdown"; 
 
          } 
 
          
 
          var remainingMinutes = Math.floor(count/60); 
 

 
          // Check if it is negative 
 
          if (remainingMinutes < 0) 
 
           location.reload(); 
 

 
          var remainingSecs = count - (remainingMinutes * 60); 
 
          if (remainingSecs < 10) { 
 
           remainingSecs = "0" + remainingSecs.toString(); 
 
          } 
 

 
          timerSpan.innerHTML = remainingMinutes + ":" + remainingSecs; 
 
         } 
 
        }
.finalCountdown {color: red;}
<div id="timerCountdown"></div>

+1

这就是为什么我们猜测代码来设置count '是问题。 –

相关问题