2017-08-13 155 views
0

我编写了一个java脚本函数来显示倒计时。但不知何故,当我启动这个计时器,它需要3-4秒的延迟,然后在html上显示计数。有人能告诉我为什么这会延迟开始。倒数计时器开始计时

var seconds = 30; 
 
var timer; 
 

 
function myFunction() { 
 
    if (seconds < 30) { 
 
    document.getElementById("countdown").innerHTML = "You are block for " + seconds + " second"; 
 
    } 
 
    if (seconds > 0) { 
 
    seconds--; 
 
    } else { 
 
    clearInterval(timer); 
 
    document.getElementById("countdown").innerHTML = ""; 
 
    } 
 
} 
 
if (!timer) { 
 
    timer = window.setInterval(function() { 
 
    myFunction(); 
 
    }, 1000); 
 
}
<div id="countdown"></div>

+0

https://developer.mozilla.org/en -US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval 延迟 以毫秒(千分之一秒)为单位的时间,计时器应延迟执行指定函数n或代码。如果此参数小于10,则使用值10。请注意,实际的延迟可能会更长;有关示例,请参阅WindowOrWorkerGlobalScope.setTimeout()中的“延迟超过指定时间的原因”。 – tibetty

+0

你应该将块更改为阻止 – user7951676

+0

并将<30改为<= 30 – user7951676

回答

1

原因有两个问题:

  1. 的setInterval不会立即启动,您需要在setInterval之前调用一次该函数。
  2. 而且,你没有显示第30秒,所以你只做了一秒钟的延迟。

var seconds = 30; 
 
var timer; 
 

 
function myFunction() { 
 
    if (seconds <= 30) { // changed to <= 30 
 
document.getElementById("countdown").innerHTML = "You are block for " + seconds + " second"; 
 
    } 
 
    if (seconds > 0) { 
 
seconds--; 
 
    } else { 
 
clearInterval(timer); 
 
document.getElementById("countdown").innerHTML = ""; 
 
    } 
 
} 
 
if (!timer) { 
 
    myFunction(); // call it once before setInterval 
 
    timer = window.setInterval(function() { 
 
    myFunction(); 
 
    }, 1000); 
 
}
<div id="countdown"></div>

-3

使用JQuery,

可以使用

只需调用jQuery框架

 $(document).ready(function(){ 
var seconds = 30; 
            var timer; 
            function myFunction() { 
             if (seconds < 30) { 
              document.getElementById("countdown").innerHTML = "You are block for " + seconds + " second"; 
             } 
             if (seconds > 0) { 
              seconds--; 
             } else { 
              clearInterval(timer); 
              document.getElementById("countdown").innerHTML = ""; 
             } 
            } 
            if (!timer) { 
             timer = window.setInterval(function() { 
              myFunction(); 
             }, 1000); 
            } 

    } 

希望这一工程

* UP DATE * 你变了,你可以调用函数只有在jQuery函数 不是整个代码

+0

jquery没有向解决方案添加任何内容,也不是问题的一部分,或者在标签中,因此不应该在答案中 – user7951676

+0

其负载首先在页面上,我没有看到任何错误 –

+0

只是使用window.onLoad – user7951676

0

试试这个,我也修正了一些拼写为你认识我可能搞砸了:

function myFunction() { 
//changed to be <= instead of just < 
if (seconds <= 30) { 
document . getElementById ("countdown"). innerHTML = "You are blocked for " + seconds + " seconds" ; } if (seconds > 0) { 
seconds --; } else { 
clearInterval (timer); 
document . getElementById ("countdown"). innerHTML = "" ; } } if (! timer) { 
timer = window . setInterval (function() { 
myFunction(); }, 1000); 
//call function immediately as well as every second afterwards 
myFunction() }