如何在零后停止倒计时

时间:2018-02-01 07:23:54

标签: javascript php countdown

我尝试创建一个javascript倒计时,然后重定向到另一个网站。

但是当它达到零并且页面加载时,倒计时开始计算-1-2等,直到重定向到另一个页面。

我在这里尝试:

function countdown(remaining) {
    if(remaining === 0)
        window.location = '<?php echo $link_redirect ?>';
    document.getElementById('countdown').innerHTML = remaining;
    setTimeout(function(){ countdown(remaining - 1); }, 1000);
};

6 个答案:

答案 0 :(得分:1)

您的页面加载需要一些时间,直到您的脚本将持续执行。您可以在else部分编写计数器减少代码。

function countdown(remaining) {
if(remaining === 0)
window.location = '<?php echo $link_redirect ?>';
else
{
    document.getElementById('countdown').innerHTML = remaining;
    setTimeout(function(){ countdown(remaining - 1); }, 1000);
}
};

答案 1 :(得分:1)

function countdown(remaining) {
    if(remaining === 0){
        window.location = '<?php echo $link_redirect ?>';
    } else{
        document.getElementById('countdown').innerHTML = remaining;
        setTimeout(function(){ countdown(remaining - 1); }, 1000);
    }
};

答案 2 :(得分:1)

简单地添加条件仅在剩余时间倒计时大于0

function countdown(remaining) {
    document.getElementById('countdown').innerHTML = remaining;
    if(remaining > 0) {
        setTimeout(function(){ countdown(remaining - 1); }, 1000);
    } else {
        window.location = '<?php echo $link_redirect ?>';
    }
;

答案 3 :(得分:0)

countdown(20);
function countdown(remaining) {
  document.getElementById('countdown').innerHTML = remaining;
  if(remaining === 0) {
    //window.location = '<?php echo $link_redirect ?>';
    document.getElementById('countdown').innerHTML = "redirect"
  } else {
    setTimeout(function(){ countdown(remaining - 1); }, 1000);
  }
};
<div id="countdown">
</div>

答案 4 :(得分:0)

你可以尝试我的例子它完美运作:

$(function(){countdown1($('#countdown1').html());})
function countdown1(remaining) {
console.log('remaining is : ' + remaining);
    if(remaining === 0)
        window.location = '<?php echo $link_redirect ?>';
    $('#countdown1').html(remaining);
    setTimeout(function(){ countdown1(remaining - 1); }, 1000);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="countdown1">10</div>

答案 5 :(得分:0)

主题的变体可能使用匿名函数

<div id='countdown'></div>
<script>
    (function( time, url ){

        /* variable used as a timer */
        var t=NaN;

        (function(){
            /* display current count */
            document.getElementById('countdown').innerHTML=time;

            /* invoke anonymous function every second */
            t=setTimeout( arguments.callee, 1000 );

            /* if the countdown has expired, clear the timer and redirect */
            if( time <= 0 ){
                clearTimeout( t );
                location.href=url;
            }
            /* reduce count */
            time--;
        })();
    /* configure time and url here */
    })( 10, 'http://www.example.com' );
</script>