views:

85

answers:

3

Hi,I'm using jquery to call some javascript functions with a delay between them.
Also I'm using Jquery Wait

When I call below function,all functions are called recpectively,there are no delays between each other.

$(this)
.call(f1)
.wait(5000)
.call(f2)
.wait(5000)
.call(f3);

Here call function calls some function as I did

$.fn.call = function (f) {
    if (f)
        f();

    return this;
};

What am i doing wrong ? How can i achieve something like this ?
Thank you

+3  A: 

If you want to call a function every 5 seconds use

setTimeout(function(){f1},5000);
setTimeout(function(){f2},10000);
setTimeout(function(){f2},15000);

if you want to call each function 5 seconds after the last one terminated use

setTimeout(function(){f1;setTimeout(function(){f2;setTimeout(function(){f3},5000);},5000);},5000);
Thariama
setTimeout() will call each function once. To call a function repeatedly, use setInterval().
Dijkstra
is there a way to achieve this in jquery ? i mean like i did
Myra
why do you need jQuery? jQuery is just a javascript framework and will work with this
Thariama
I know what jquery is.For later use,I will have animations work with this code,that's why i should stick with jquery.Your implementation is also correct +1
Myra
+2  A: 

You don't need wait() from that cookbook; delay() is built-in and appears to have the same functionality. But either function involves adding something to jQuery's internal queue of effects and then removing it after a timeout expires, i.e. it's not a sleep statement, so it's not going to wait around before returning.

If you want to use delay() or wait(), you should make call() enqueue the function with queue(). Just sketching, but something like:

$.fn.call = function(f) {
    if (f) {
        $(this).queue(function() {
            f();
            $(this).dequeue();
        }
    }
    return this;
}

Then I'd expect your code to work the way you intend.

Isaac Cambron
your code is not working properly :(
Myra
Well, it was just a sketch to get you in the right direction, insofar as using wait/delay is concerned. I haven't actually tried it, so it might take some tweaking. Look carefully at the documentation for queue(), and try some of their examples.
Isaac Cambron
+1  A: 

Here is a function that calls in sequence an array of function:

$.fn.callFn = function(fns, delay) {
    var fn, that = this;
    if(fns.length > 0){
        fn = fns.shift()
        fn && fn();
        setTimeout(function(){
            that.callFn(fns, delay);
        }, delay);
    }
    return this;
};

And you would call it like that:

$(this).callFn([f1, f2, f3], 2000);
Mic
I will have animations work with my code($(this).call(f1).wait(5000).call(f2).wait(5000).animate(...).wait(1000).call(f3);),that's why i should stick with jquery.
Myra