就我而言,我只想在前一个函数完成后才调用 document.getElementById
,但结果恰恰相反:它首先(或同时)执行先是文档调用,然后是函数。
在我的具体情况下,我有一个火箭和一个计数器:火箭图像必须在执行 contatore()
函数后发生变化。
这是我的功能:
function rocketLaunch(){
contatore(10);
document.getElementById("imgRazzo").src = imgRazzoAcceso.src;
}
这里是 contatore
函数,它使用 setTimeout
:
function contatore(number){
/* if 0, we have to stop the counter and return to the caller */
if(number == 0){
return;
}else{
/* js recursive: wait 1 second, than re-call this function with number-1 as parameter*/
setTimeout(function(){contatore(number - 1)}, 1000);
/* you can finally inner the html */
document.getElementById("main").innerHTML = number;
}
}
最佳答案
我打赌你的函数中有一些超时/间隔/ajax 调用。这就是为什么它是异步的。您需要声明回调,将其作为参数传递,并在完成时调用 contatore();
。
示例:
var contatore = function(callback) {
//do stuff here
callback();
}
var afterFinishedFunction = function(){
// this will execute when contatore finishes
}
// make it together
contatore(afterFinishedFunction); // (note, there is no brackets like this afterFinishedFunction()
关于Javascript - 在函数完成后执行文档调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40961712/