使用jQuery的javascript clearTimeout问题

时间:2013-11-27 00:54:38

标签: javascript jquery timer

我做了2次倒计时事件,但是后来使用clearTimeout我无法停止setTimeout(countDown)函数。这是我的jQuery:

$(document).ready(function () {
var lives = 5
var livesmenos1 = "4";
var livesmenos1 = 4;
var countdownfinal = 10;
var t;
var isTimeron = false;
var onelive = "1";
var onelive = 1;

$(".wrongbutton, .wrongbutton2, .wrongbutton3").click(function () {
    $(".countdownfirst").text(livesmenos1)
    livesmenos1--;
    if (livesmenos1 == 0) (livesmenos1 = 0);
    if (livesmenos1 < 2)
        $(".countdownfirst").css({ "color": "990099", "font-size": "380%" });
    if (livesmenos1 < 1)
        $(".lives").attr("src", "images/morelives.gif");
    if (livesmenos1 < 0)
        $("#tableone, #tabletwo").delay(1000).hide(2000);
    if (livesmenos1 < 0)
        $("#tableloser").delay(2000).fadeIn(2500, function countDown() {
            setTimeout(countDown, 1000);
            $("#box").text(countdownfinal + " seconds").css({ "color": "990099" });
            countdownfinal--;
            if (countdownfinal < 1) (countdownfinal = 10);
            if (countdownfinal < 2)
                $(".countdownfirst").text(onelive++);
            if (onelive > 5)
                $(".countdownfirst").text("5");
            if (onelive > 1)
                $("#nextbuttonloser").delay(1000).fadeIn(500).delay(30000);
        });
 });
});

然后我做了myStopFunction onclick按钮来启动clearTimeOut函数:

function myStopFunction()
{
clearTimeout(countDown);
}

它不起作用。我也尝试使用jQuery触发,但又没有效果。如何停止名为“countDown”的setTimeout函数?

谢谢

1 个答案:

答案 0 :(得分:1)

无法阻止特定功能在Timeout中触发。唯一的方法是停止超时本身。每次超时在调用时返回一个整数值。使用此值清除超时。请注意,它需要可用于您的函数范围

var TimeoutHandle;
$(document).ready(function () {
 ...
 TimeoutHandle = setTimeout(countDown, 1000);
 ...
});

function myStopFunction()
{
 clearTimeout(TimeoutHandle);
}