noboruwatanabe
noboruwatanabe

Reputation: 309

jQuery pause function execution and do something else while paused

I have something like this:

function doSomething() {
   var obj = $('somediv');

   ...

   waitAndDoSomethingElse(obj);

   ...

   $('somediv').show();
   ...
}


function waitAndDoSomethingElse(obj) {
   obj.fadeIn();
   ....
}

I want doSomething() to pause... execute waitAndDoSomethingElse() and then continue... Any ideas?

Thank you

EDIT:

I'll try to explain better, sorry if my question was confused...

function showSomething() {
   var whatToShow = $('#div');

   doSomethingElse();

   whatToShow.fadeIn('slow');
}


function doSomethingElse() {
   $('#someDiv').appendTo($('#someOtherDiv'));
   $('#somethingElse').fadeIn('slow');
   ...
}

In this example whatToShow.fadeIn will fire without waiting for doSomethingElse to end...

Upvotes: 0

Views: 2240

Answers (2)

redsquare
redsquare

Reputation: 78667

Use the animation callbacks. All the animations have them as the last arg. See here for the fadeIn docs.

 $('#someElement').fadeIn('slow', callbackFn);


   function callbackFn(){
       //executed after the fadeIn is complete
   }

If you are not using the animation helpers then you can use the same methodology and pass callback functions to other functions which can choose when to call the callback.

var callbackFn = function(){ //do something };

doSomething( callbackFn )

function doSomething( callback ){

    doOtherStuff();
    //call the callback
    callback && callback()

}

Another option is to use window.setTimeout to fire a function after x milliseconds.

Upvotes: 4

Elzo Valugi
Elzo Valugi

Reputation: 27856

Do this

function doSomething() {
    var obj = $('somediv');
    ...
    waitAndDoSomethingElse(obj);
}


function waitAndDoSomethingElse(obj) {
    obj.fadeIn();
    // if you want a pause here you can also add the next call in a setTimeout()
    $('somediv').show(); // this call is executed only after
}

Upvotes: 0

Related Questions