Javascript - 在函数完成后执行文档调用

标签 javascript html dom

就我而言,我只想在前一个函数完成后才调用 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/

相关文章:

asp.net - 编码 HTML 页面标题的正确方法

javascript - 如何将 onclick 事件添加到表列?

javascript - 检测URL阻止的js ajax

javascript - Bootstrap 3 模式表单不触发 jQuery .submit()

javascript - JSONSchema - 依赖于父属性的必需属性

html - 如何在 CSS3 下拉菜单中使用(顶部)边距?

html - 为什么在以下情况下两个内联 block 元素都会掉落?

javascript - Json 编码不起作用

javascript - jQuery Force 为 iframe 设置 src 属性

javascript - 在 href 中插入图像的最佳方法