Skip to content Skip to sidebar Skip to footer

Queuing Actions (not Effects) To Execute After An Amount Of Time.

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

Solution 1:

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);

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)
;

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

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

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

or to call with args pass arguments in an array:

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

Solution 2:

The jQuery FxQueues plug-in does just what you need:

$('#element').fadeOut({
    speed: 'fast',
    preDelay: 5000
});

Post a Comment for "Queuing Actions (not Effects) To Execute After An Amount Of Time."