I write a java script function to show a count down. But somehow when i start this timer it take 3-4 sec delay and then show count down on html. Can someone tell me why it taking this delay in start.
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 :(得分:1)
有两个原因:
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);
}
&#13;
<div id="countdown"></div>
&#13;
答案 1 :(得分: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() }
答案 2 :(得分:-3)
using JQuery ,
You can Use
Just Call the JQuery FrameWork
$(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);
}
}
Hope That works
*UP DATE * you changed the question you can call the Function only in the jquery Function Not the Whole Code