user3144310
user3144310

Reputation:

.delay to function Jquery

If I have a function

function hello() {
    alert("hello world!");
}

and I want to call it, I just do hello(), but if I want to do a delay? Should I do:

$.delay(3000).hello();

Would this work?:

$.fn.hello = function() {
    alert("hello world!");
}
$.delay(...).hello()

Upvotes: 1

Views: 58

Answers (2)

adeneo
adeneo

Reputation: 318172

You can always just add to the queue

$.fn.hello = function() {
    alert("hello world!");
    return this;
}

$(document).delay(3000).queue(function() {
    $(this).hello().dequeue();
});

FIDDLE

The reason it only works on animations, is because those are added to the FX queue automagically, but anything can be queued and dequeued in jQuery, you can even create your own custom queues that will work with delay()

For a custom queue you can do something like this

$({}).delay(3000, 'custom').queue('custom', function( next ) {
    $(this).hello();
}).dequeue('custom');

FIDDLE

This is a little different, it's showing us that we can use an empty jQuery object as the holder and not just an element, and the second argument in delay() is used to pass in the name of the queue, which we then attach and dequeue a little differently.

We're not really using the next argument as there is nothing more in the queue to call, but it's an argument that you call to go the next step, as in you'd call next() inside the function to proceed.

Upvotes: 2

Igor
Igor

Reputation: 33963

Is this homework, or some code golf problem? Because setTimeout is really the ideal function in this case, and delay won't work because it's just for jQuery effects/animations.

I suppose you could use setInterval and clear after the first invocation. Something like:

var interval;

function hello() {
    clearInterval(interval);
    alert("hello world!");
}

interval = setInterval(hello, 3000);

If you can't alter the hello() function or use it elsewhere, you can create a wrapper function for the setInterval call, and use that instead.

Upvotes: 2

Related Questions