简体   繁体   English

创建倒数计时器并在倒数归零后重定向到另一页

[英]Create a countdown timer and redirect to another page after countdown comes to zero

I want create a countdown timer for som sections of my asp.net sites with javascript. 我想用JavaScript为我的asp.net网站的som部分创建一个倒数计时器。
The timer starts from various minutes or seconds. 计时器从不同的分钟或秒开始。 After countdown comes to zero, I want stop the timer tick and do somethings like redirect to another page. 倒数归零后,我想停止计时器计时并执行类似重定向到另一页的操作。
I've found this code from google and it's ok, but never stop after countdown comes to zero. 我已经从Google找到了此代码,没关系,但在倒数为零后再也不会停止。 please help me to fix this bug. 请帮助我修复此错误。

<head>
<script>
    function startTimer(duration, display) {
        var timer = duration, minutes, seconds;
        setInterval(function () {
            minutes = parseInt(timer / 60, 10)
            seconds = parseInt(timer % 60, 10);

            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            display.textContent = minutes + ":" + seconds;

            if (timer-- < 0) {
                //window.location = "http://www.example.com";
                clearInterval(timer);
            }
        }, 1000);
    }

    window.onload = function () {
        var fiveMinutes = 60 * 5,
            display = document.querySelector('#time');
        startTimer(fiveMinutes, display);
    };
</script>
</head>
<body>
    <div>Registration closes in <span id="time">05:00</span></div>
    <form id="form1" runat="server">

    </form>
</body>

You have to clear what setInterval return. 您必须清除setInterval返回的内容。 Something like this. 这样的事情。

 <script> function startTimer(duration, display) { var timer = duration, minutes, seconds; var end =setInterval(function () { minutes = parseInt(timer / 60, 10) seconds = parseInt(timer % 60, 10); minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.textContent = minutes + ":" + seconds; if (--timer < 0) { //window.location = "http://www.example.com"; clearInterval(end); } }, 1000); } window.onload = function () { var fiveMinutes = 5, display = document.querySelector('#time'); startTimer(fiveMinutes, display); }; </script> </head> <body> <div>Registration closes in <span id="time">05:00</span></div> <form id="form1" runat="server"> </form> 

Gotrank's accepted answer is great - one small bug though: Gotrank接受的答案很好-尽管有一个小错误:

    var fiveMinutes = 5,

...should be... ...应该...

    var fiveMinutes = 300,

...for five minutes (it is currently 5 seconds). ...持续五分钟(目前为5秒)。 I would have commented, but I don't have enough reputation points yet. 我本来可以发表评论,但我的信誉点还不够。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM