我想在JavaScript中的一个setTimeout()
的末尾调用两个函数。
是否可以,如果"is",将首先执行哪个?
setTimeout(function() {
playmp3(nextpage);
$.mobile.changePage($('#' + nextpage));
}, playTime);
最佳答案
是的,为什么不呢? setTimeout
的第一个参数为回调函数。它是一个回调函数,这一事实不会改变任何东西。通常的规则适用。
除非您使用基于Promise
或基于回调的代码,否则Javascript会顺序运行,因此将按照您编写函数的顺序来调用它们。
setTimeout(function() {
function1() // runs first
function2() // runs second
}, 1000)
但是,如果您这样做:
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)
然后顺序会更改,因为
setTimeout
是异步的,在这种情况下,它会在计时器到期后被触发(JS继续执行并同时执行function2()
)如果上述代码有问题,则您的任何一个函数都包含异步代码(
setInterval()
,setTimeout()
,DOM事件,WebWorker代码等),这会使您感到困惑。