javascript 依次执行函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5978892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
execute function after another
提问by cmplieger
I have this javascript code:
我有这个 javascript 代码:
if (direction !== "leftnav") {
// 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?
是否可以在第一个之后执行 2e 函数而不必使用超时事件?
thanks for your help!
感谢您的帮助!
回答by pixelbobby
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
}
回答by Robert
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.
如果 if 语句中的内容被阻塞,Javascript 将从上到下运行。如果是这样,您可以将代码放在 if 语句的正下方,在超时之外,它会正常运行。如果它是异步的,您可以使用在第一个函数完成时触发的回调来启动第二个函数。
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.
下面提供的示例并不是真正有效的做事方式,但更多地用于说明我在上面所说的内容。在该write()
函数中,您可能正在执行 AJAX 调用,或者等待用户单击某些内容,或者您有什么。解释器继续到下一行,该部分将立即写入,并按阻塞顺序进行。
JS
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
回答by pantunas
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
.
像这样,bar
会在之前被调用foo
。