Jquery杀死不需要的超时

时间:2013-05-08 18:24:28

标签: jquery timeout

所以我有2个按钮。

按钮a:是一个按钮。的(#按钮1)

按钮b:假提交按钮。的(#right_r)

按钮c:提交按钮。的(#右)

默认情况下,按钮A会显示,并会在点击时阻止默认()并显示错误消息。

当我点击按钮A时,它将设置超时8000,因此在8秒内,它将用按钮C替换按钮B.

但问题是:

当用户多次点击按钮A时,会设置很多超时。

我想要做的是,在设置新超时之前杀死之前的超时,like stop it.

我的代码:

$(document).ready(function() {
    $("#right_r").click(function(event) {
        event.preventDefault();
        $("#error").slideDown("slow");

        setTimeout(function() {
            $("#error").slideUp("slow");    
        }, 1000);
    });
    $("#button1").click(function() {
        setTimeout(function() {
            $("#right_r").hide();
            $("#right").show();
        }, 8000);
    });
});

感谢。

2 个答案:

答案 0 :(得分:0)

如果您使用内置延迟方法,这将很容易..

$("#error").stop(true,true).slideDown("slow").delay(1000).slideUp("slow")

但请注意.delay()只会延迟动画方法和.queue方法。

答案 1 :(得分:0)

试试这个

var right_r_timeout = null, runelocus_timeout = null;
$(document).ready(function() {
    $("#right_r").click(function(event) {
        event.preventDefault();
        $("#error").slideDown("slow");

        if (right_r_timeout != null) {
            clearTimeout(right_r_timeout);
            right_r_timeout = null;
        }
        right_r_timeout = setTimeout(function() {
            $("#error").slideUp("slow");
        }, 1000);
    });

    $("#runelocus").click(function() {
        if (runelocus_timeout == null) {
            clearTimeout(runelocus_timeout);
            runelocus_timeout = null;
        }
        runelocus_timeout = setTimeout(function() {
            $("#right_r").hide();
            $("#right").show();
            runelocus_timeout = null;
        }, 8000);
    });
});

请参阅https://developer.mozilla.org/en/docs/DOM/window.setTimeout