Jquery synchronous functions

Is there a way to run a function after performing other functions? For example:

doSomething();
doSomethingElse();

I want doSomethingElse () to fire after doSomething completes. is it possible?

+5
source share
5 answers

If your function doSomething()does something asynchronously (for example, makes an Ajax request), you need to make a doSomethingElse()callback for this asynchronous request, instead of executing it immediately after returning doSomething().

+7
source

You can actually do what you want with jQuery (at least in a sense). This can be considered a bit hacked, but it works flawlessly.

, . - div.

<div id="syncFnHolder"></div>

JS + runMe.

function doSomething() { alert("First"); }
function doSomethingElse() { alert("Second"); }
function doSomethingElseThree() { alert("Third"); }

function runMe(fn, selec) {
    return function() {
        fn();
        setTimeout(function() {
            $(selec).dequeue("syncFnQueue");
        }, 1000);
    } 
};

var selector = "#syncFnHolder";
//add three functions to a queue
$(selector).queue("syncFnQueue", runMe(doSomething, selector));
$(selector).queue("syncFnQueue", runMe(doSomethingElse, selector));
$(selector).queue("syncFnQueue", runMe(doSomethingElseThree, selector));
//start first function in queue (FIFO) others are triggered automatically
$(selector).dequeue("syncFnQueue");

1: "", "", "".

, setTimeout $(selec).dequeue("syncFnQueue");.

, . doSomething(x,y,z) runMe, , - . .

javascript

+6

....

function doSomething(callback) {
    // code for do some thing
    // now fire off the callback
    if (typeof callback === 'function') {
        callback();
    }
}

function doSomethingElse() {
}

doSomething(doSomethingElse);
+3

.

, . .

, , - JavaScript, jQuery-aop.

+2

, , doSomething() , doSomethingElse() :

  retval = doSomething();
  doSomethingElse(retval);

, , - doSomethingElse(), , , , ... , , doSomething(), . .

.

-1

All Articles