开发者

execute function after another

开发者 https://www.devze.com 2023-03-05 04:32 出处:网络
I have this javascript code: if (direction !== \"lef开发者_Go百科tnav\") { // DO THINGS }; setTimeout(function () {

I have this javascript code:

 if (direction !== "lef开发者_Go百科tnav") { 
// DO THINGS
};
setTimeout(function () {
//DO OTHER THINGS AFTER THE FIRST THING
}, 1000);

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

thanks for your help!


Yes it's possible. Here's an example using the only code you've provided:

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

    // THEN
    doOtherThings();

    // THEN
    doMoreThings();
}; 

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


Javascript will run from top to bottom if what you have in that if statement is blocking. If so, you can just put the code right below the if statement, outside of a timeout and it will run normally. If it's asynchronous, you can use a callback that fires when the first function is completed to start the second function.

The example provided below is not really efficient way of doing things, but is more used to illustrate what I'm talking about above. Within the write() function you may be doing an AJAX call, or waiting for the user to click something, or what have you. The interpreter continues on to the next line which section which will just write right away, and in blocking order.

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/>");

Output

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

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


You just need to call functions with the order you want

function foo(){
//code
}

function bar(){
//other
}

bar();
foo();

Like this, bar will be called before foo.


use javascript promise and Promise.all

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号