在一段时间后执行排队操作(不是效果)。 [英] Queuing actions (not effects) to execute after an amount of time.

查看:75
本文介绍了在一段时间后执行排队操作(不是效果)。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道的是,如果有一种很好的方法可以在一段时间后对jQuery函数进行排队。这不会暂停其他函数的执行,只会暂停链中的后续函数。也许我想象的一个例子就是:

What I'd like to know is if there is a nice way to queue jQuery functions to execute after a set amount of time. This wouldn't pause the execution of other functions, just the ones following in the chain. Perhaps an example of what I'd envisage it would look like would illustrate:

$('#alert')
    .show()
    .wait(5000)    // <-- this bit
    .hide()
;

我知道通过使用超时可以实现,但似乎这是一种混乱的方式,特别是与上面的例子相比(如果它是真的)。​​

I know that it's possible by using timeouts, but it seems like that's a messy way to do it, especially compared to the above example (if it were real).

那么,jQuery已经内置了这样的东西,如果没有,那么最好的方法是什么模仿它?

So, is something like this already built-in to jQuery, and if not, what is the best way to emulate it?

推荐答案

你不能这样做,而你可能不想这样做。虽然它看起来很漂亮,但Javascript中没有任何机制可以让你做到这一点,而不只是循环等待直到时间过去。你当然可以这样做,但你冒着严重降低浏览器性能的风险,如果你的超时时间超过几秒钟,浏览器会向用户显示你的javascript似乎卡住的警告。

You can't do that, and you probably don't want to. While it certainly looks pretty, there is no mechanism in Javascript that will allow you do to that without just looping in "wait" until the time has passed. You could certainly do that but you risk seriously degrading the browser performance and if your timeout is longer than a handful of seconds browsers will show a warning to the user that your javascript seems to be stuck.

执行此操作的正确方法是超时:

The correct way to do this is with timeouts:

var el = $('#alert');
el.show()
setTimeout(function() { el.hide() }, 5000);

你的另一个选择是扩展jquery,为你想要延迟的行动添加一个效果: / p>

Your other option would be to extend jquery to essentially add an effect for actions you want to delay:

jQuery.fn.extend({
    delayedHide: function(time) {
        var self = this;
        setTimeout(function() { self.hide(); }, time);
    }
});

$('#alert')
    .show()
    .delayedHide(5000)
;

您还可以使用类似于setTimeout的方法扩展jquery:

You could also extend jquery with a method similar to setTimeout:

jQuery.fn.extend({
    delayThis: function(fn, time, args) {
        var self = this;
        setTimeout(function() { jQuery.fn[fn].apply(self, args); }, time);
    }
});

$('#alert')
    .show()
    .delayThis('hide', 5000)
;

或用数组中的args传递参数调用:

or to call with args pass arguments in an array:

$('#alert')
    .show()
    .delayThis('css', 5000, [ 'display', 'none' ])
;

这篇关于在一段时间后执行排队操作(不是效果)。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆