我正在尝试制作一个简单的 javascript 倒数计时器,每隔一秒将按钮中的值从 3 更改为 1。我的代码可以正常工作,但它使用了很多功能。我想知道我是否可以减少使用。我试图将倒计时放在一个显示 i 值的 for 循环中,但它似乎无法正常工作。
这是我的代码:
function launch( )
{
document.getElementById("blast").value = "Preparing to launch...";
setTimeout ( "countdown3()", 1000 );
}
function countdown3()
{
document.getElementById("blast").value = "3";
setTimeout("countdown2()", 1000);
}
function countdown2()
{
document.getElementById("blast").value = "2";
setTimeout("countdown1()", 1000);
}
function countdown1()
{
document.getElementById("blast").value = "1";
setTimeout("GO()", 1000 );
}
function GO()
{
document.getElementById("blast").value = "BLAST OFF";
move();
}
最佳答案
这个怎么样:
function launch(seconds, id, message, callback)
{
var target = document.getElementById(id);
target.innerHTML = message;
var countDownId = setInterval( function(){
target.innerHTML = seconds;
if(seconds == 0){
clearInterval(countDownId);
callback(target);
}
seconds--;
}, 1000 );
}
function GO(target)
{
target.innerHTML = "BLAST OFF";
move();
}
launch(3, "blast", "Preparing to launch...", GO);
关于Javascript倒计时设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10024625/