【问题标题】:Execute after cleartimeout function finished (jQuery)cleartimeout 函数完成后执行 (jQuery)
【发布时间】:2012-03-29 17:24:26
【问题描述】:

我有这种情况。我有一个 setTimeout 到一个函数,我在其中淡出和淡入一个元素。在几秒钟内,这个超时被 cleartimeout 清除,然后调用 .hide() 来隐藏这个元素。问题是有时它不会隐藏元素。我感觉这和时间有关系。

例子:

function first_func(){
    $('.element').fadeOut(function(){
        // Do other stuff like change element's position
        $('.element').fadeIn();
    });

    interval1 = setTimeout(function(){first_func()},500);           
}

function second_func(){
    countdown--;
    if (countdown<0){
        last_func();
    }
    interval2 = setTimeout(function(){second_func()},1000);         
}

function begin_func(){
    first_func();
    second_func();
}

function last_func(){
    clearTimeout(interval1);
    clearTimeout(interval2);
    $('.element').hide();
}

所以基本上问题是在 last_func 中我清除了间隔并隐藏了元素,但有时该元素在页面上仍然可见。所以我猜它确实隐藏了,但间隔仍在进行中,它会淡入。

如果有人有什么建议,请

【问题讨论】:

    标签: javascript jquery intervals


    【解决方案1】:

    只是一个建议,但这一点对我来说似乎是错误的:

    function second_func(){
        countdown--;
        if (countdown<0){
            end_func();
        }
        interval2 = setTimeout(function(){second_func()},1000);         
    }
    

    即使你调用 end_func() 来停止一切,你也会在此之后设置一个新的超时。

    function second_func(){
        countdown--;
        if (countdown<0){
            end_func();
        } else {
            interval2 = setTimeout(second_func, 1000);
        }       
    }
    

    另外提示:为了避免运行fadeIn/fadeOuts影响元素的隐藏,你应该清空动画队列:

    $('.element').stop(true, true).hide();
    

    【讨论】:

    • 对不起,我一直在写,我现在没有实际的来源。当然在调用 end_func(); 之后我确实回来了;也是。基本上一切都很好,只是有时元素没有隐藏
    • @Tom 好的,但考虑在调用 hide 之前添加stop(true, true),这可能会有所帮助。
    • 好吧,我想最好给你看看真实的代码,你可以在 www.tomasdostal.com/projects/thirst_game 上看到它。但是代码很乱
    • 是的,我可以重现该问题。另一种解决方案可以不只是隐藏水滴,而是将其与 DOM 完全分离:$('.element').detach(); - 如果以后再次需要它,则需要将 jQuery 对象存储在一个变量中,然后重新附加它。跨度>
    • 抱歉,忽略了 stop() 注释,看起来效果很好,谢谢!
    【解决方案2】:

    fadeIn和fadeOut默认使用400毫秒的持续时间,你可以通过设置第一个参数来改变它。

    $('.element').fadeOut( [duration] [, callback] );
    

    【讨论】:

    • 这只是一个例子,在我的脚本中我将持续时间设置为 50
    【解决方案3】:

    你似乎从不调用 last_func,end_func() 应该是 last_func() 吗?

    这有效: http://jsfiddle.net/CZ9hr/1/

    我可以为您似乎想要实现的目标提出一种更简单的方法:http://jsfiddle.net/fSEjR/2/

    var countdown = 3,
        $element = $('.element');
    
    for (var i = 0; i < countdown; i++) {
        $element.fadeOut().fadeIn(function() {
            countdown--;
            if (countdown === 0) $element.hide();
        });
    };
    

    这是因为动画在 jquery 中自动排队。

    【讨论】:

    • 你可以自己查看www.tomasdostal.com/projects/thirst_game,有时候元素不隐藏
    猜你喜欢
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2020-01-31
    相关资源
    最近更新 更多