尽管付出了努力,递归时钟呼叫仍然在嘀嗒作响?

时间:2012-07-20 19:36:54

标签: javascript clock

我有一个时钟,我想继续滴答作响,除了,当我把" break"进入"秒"参数。当我把" break"时,时钟休息一秒钟,然后继续滴答作响。我想让它停止滴答作响,我不知道问题是什么。为了记录,我在页面加载时调用此函数,然后每当用户单击页面上的元素时。点击后会发现它变得棘手。

var seconds;

function countdown_clock(seconds) {
    if (seconds != "break") {
        countdown(seconds);

        seconds = seconds;
    }
}

function displaymessage() {
    alert("Your Time Has Expired");
}

function countdown(seconds) {
    if (seconds != "break") {
        Time_Left = seconds;
        format = 1;

        if (Time_Left < 0)
            Time_Left = 0;

        switch (format) {
            case 0:
                //The simplest way to display the time left.
                $("div#ClockCountdown").html(Time_Left + ' seconds');
                break;
            case 1:
                //More detailed.
                Next_time = Time_Left - 1;
                minutes = Math.floor(Time_Left / 60);
                Time_Left %= 60;
                seconds = Time_Left;

                mps = 's';
                sps = 's';
                earlyzero = '';
                latezero = '';
                //ps is short for plural suffix.

                if (minutes == 1) mps = '';
                if (seconds == 1) sps = '';
                if (seconds < 10) earlyzero = '0';
                //                    if(seconds == 10) latezero ='0';

                //                    document.all.countdown.innerHTML = minutes + ' minute' + mps + ' and ';
                //                    document.all.countdown.innerHTML += seconds + ' second' + sps;

                innerHTML = minutes + ':';
                innerHTML += earlyzero + seconds;
                $("div#ClockCountdown").html(innerHTML + "nonbroken!");
                break;
            default:
                $("div#ClockCountdown").html(Time_Left + ' seconds');
        }

        if (Next_time == 0) {
            displaymessage();
            window.location.href = "navigation.php?nav=video_timeout";
        }
        else {
            setTimeout('countdown(' + Next_time + ');', 1000);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您还必须清除超时。做这样的事情:

var timeout;
function countdown(seconds) {
    if (seconds == "break") {
        clearTimeout(timeout);
    }
    // other things
    if( Next_time == 0) {
        displaymessage();
        window.location.href ="navigation.php?nav=video_timeout";
    } else {
        timeout = setTimeout('countdown(' + Next_time + ');', 1000);
    }
}

答案 1 :(得分:0)

超时是一次拍摄,在调用超时功能时会被清除。只有在秒!=='break':

时才应设置下一个超时
    if (Next_time == 0) {
        displaymessage();
        window.location.href = "navigation.php?nav=video_timeout";
    }
    else if (seconds !== 'break') {
        setTimeout('countdown(' + Next_time + ');', 1000);
    }