计时器在时间结束时发出警报

时间:2014-12-01 17:43:42

标签: javascript timer countdowntimer

我制作了一个倒数计时器。它会在时间到来时发出警报/弹出窗口。 我写了这样的代码:

function cd(){
now = new Date();
diff = end - now;
diff = new Date(diff);
var sec = diff.getSeconds();
var min = diff.getMinutes();

if(now >= end)
    {
    clearTimeout(timerID);

    window.alert("Time is up. Press OK to continue.");
    document.forms[0].submit();
    }
    else
    {
    document.getElementById("cdtime").innerHTML =  min + ":" + sec;
    }
    timerID = setTimeout("cd()", 10); 
}
window.onload = cd

这是自动提交计时器。当时间到了,它将提交表格。问题是,当我window.alert时,即使点击“ok”,它也会保持警惕。点击“确定”后我该怎么做才会重定向到document.forms[0].submit()

3 个答案:

答案 0 :(得分:0)

试试这个:

if (window.confirm(‘put stuff here’)) {
window.location.href=‘put link here’;
}
else {
var x = "";
}

答案 1 :(得分:0)

timerID = setTimeout("cd()", 10);始终在您的代码中执行。它应该在else块内。此外,无需清除超时

(如果您使用setInterval()函数而不是setTimeout(),则必须清除间隔)...

试试这个。

function cd(){
    now = new Date();
    diff = end - now;
    diff = new Date(diff);
    var sec = diff.getSeconds();
    var min = diff.getMinutes();

    if(now >= end)
        {
        window.alert("Time is up. Press OK to continue.");
        document.forms[0].submit();
        }
    else
        {
        document.getElementById("cdtime").innerHTML =  min + ":" + sec;
        setTimeout("cd()", 10); 
        }
    }
window.onload = cd;

答案 2 :(得分:0)

您的计时器每隔10毫秒启动一次,因此警报实际上正在刷新,

setTimeout keeps firing

阅读本文,给你一个更好的主意,希望有所帮助