RAH*_*EEP 5 javascript jquery jquery-mobile
我想setTimeout()在JavaScript中调用两个函数.是否有可能,如果"是"哪一个将首先执行?
setTimeout(function() {
playmp3(nextpage);
$.mobile.changePage($('#' + nextpage));
}, playTime);
Run Code Online (Sandbox Code Playgroud)
Nik*_*des 15
可能吗?
是的,为什么不呢?setTimeout采用回调函数作为它的第一个参数.事实上它是一个回调函数并没有改变任何东西; 通常的规则适用.
哪一个会先被执行?
除非您使用Promise基于回调的代码或基于回调的代码,否则Javascript会按顺序运行,因此您的函数将按照您记下的顺序调用.
setTimeout(function() {
function1() // runs first
function2() // runs second
}, 1000)
Run Code Online (Sandbox Code Playgroud)
但是,如果你这样做:
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)
Run Code Online (Sandbox Code Playgroud)
然后订单更改,因为setTimeout是异步,在这种情况下它会在计时器到期后被解雇(JS继续并function2()在此期间执行)
如果你与你的上述代码的问题,然后你的函数或者一个包含异步代码(setInterval(),setTimeout(),DOM事件,WebWorker代码等),其迷惑你.