Perform a function after another

I have this JavaScript code:

 if (direction !== "leftnav") { 
// DO THINGS
};
setTimeout(function () {
//DO OTHER THINGS AFTER THE FIRST THING
}, 1000);

Is it possible to execute function 2e after the first instead of using a timeout event?

Thank you for your help!

+3
source share
4 answers

Yes it is possible. Here is an example using only the code you provided:

if (direction !== "leftnav") {  
    // DO THINGS...

    // THEN
    doOtherThings();

    // THEN
    doMoreThings();
}; 

var doOtherThings = function(){
    //DOING OTHER THINGS
}
var doMoreThings = function(){
    //DO EVEN MORE THINGS
}
+9
source

Javascript will work from top to bottom if what you have in this case is a lock. If so, you can simply put the code directly under the if statement, outside the timeout, and it will work fine. If it is asynchronous, you can use a callback that fires when the first function is completed to start the second function.

-, , . write() AJAX , - . , , , .

JS

var write = function (v, cb) {
    setTimeout(function() {
        document.write(v);
        cb && cb();
    }, 1000);
}

if (true) {
    write("I'm not blocking, blah<br/>", function() {
        document.write("Running<br/>");
    });
}

if (true) {
    document.write("I'm blocking, blah<br/>");
}
document.write("Running<br/>");

I'm blocking, blah
Running
I'm not blocking, blah
Running

http://jsfiddle.net/robert/vvmyk/

+7

You just need to call the functions with the desired order

function foo(){
//code
}

function bar(){
//other
}

bar();
foo();

Similarly, barwill be called before foo.

0
source

use javascript promise and Promise.all

0
source

All Articles