javascript 在 setTimeout 中调用 1 个以上的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29839996/
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
Calling more than 1 function in setTimeout
提问by RAHUL DEEP
I want to call two functions at the end of one setTimeout()
in JavaScript.
Is it possible and if "yes" which one will be executed first?
我想setTimeout()
在 JavaScript 中的一个函数的末尾调用两个函数。是否有可能,如果“是”,将首先执行哪一个?
setTimeout(function() {
playmp3(nextpage);
$.mobile.changePage($('#' + nextpage));
}, playTime);
回答by nicholaswmin
Is it possible?
是否可以?
Yes, why wouldn't it be? setTimeout
takes a callback functionas it's 1st argument. The fact that it's a callback function doesn't change anything; the usual rules apply.
是的,为什么不呢?setTimeout
需要一个回调函数,因为它是第一个参数。它是一个回调函数这一事实不会改变任何东西;通常的规则适用。
which one will be executed first?
哪个会先执行?
Unless you're using Promise
-based or callback-based code, Javascript runs sequentiallyso your functions would be called in the order you write them down.
除非您使用Promise
基于或基于回调的代码,否则Javascript将按顺序运行,因此您的函数将按照您写下的顺序调用。
setTimeout(function() {
function1() // runs first
function2() // runs second
}, 1000)
However, if you do this:
但是,如果您这样做:
setTimeout(function() {
// after 1000ms, call the `setTimeout` callback
// In the meantime, continue executing code below
setTimeout(function() {
function1() //runs second after 1100ms
},100)
function2() //runs first, after 1000ms
},1000)
then the order changes since setTimeout
is asyncin which case it get's fired afterit's timer expires (JS continued and executed function2()
in the meantime)
然后顺序发生变化,因为setTimeout
是异步的,在这种情况下,它会在计时器到期后被触发(JS 继续并function2()
在此期间执行)
If you have issues with your above code then either one of your functions contains asynccode (setInterval()
,setTimeout()
, DOM event, WebWorker code etc), which confuses you.
如果您的上述代码有问题,那么您的任一函数都包含异步代码(setInterval()
、setTimeout()
、 DOM 事件、WebWorker 代码等),这会让您感到困惑。
- asynchere stands for asynchronousmeaning not occurring in a particular order
- 这里的async代表异步,意思是不按特定顺序发生
回答by Carmine Checker
I've used this syntax and it works fine:
我已经使用了这种语法,它工作正常:
$('#element').on('keypress change', function (e) {
setTimeout(function () { function1(); function2(); }, 500, $(this));
});