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



在我的情况下,我想做的是呼叫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()

使用await

function rocketLaunch(){
  await contatore();
  document.getElementById("imgRazzo").src = imgRazzoAcceso.src;
}

关于其工作原理的演示

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
  console.log('Taking a break...');
  await sleep(2000);
  console.log('Two second later');
}
demo();

sleep的语法是从此链接中

取。

您可以通过回调进行操作:

// dummy image, just for this demo:
var imgRazzoAcceso = {
    src: 'https://cdn.pixabay.com/photo/2014/04/03/11/58/rocket-312767_1280.png'
};
function rocketLaunch(){
  contatore(10, function () { // callback
    document.getElementById("imgRazzo").src = imgRazzoAcceso.src;
  });
}
function contatore(number, done){
    document.getElementById("main").textContent = number;
    if(number) {
        // use bind for shorter syntax. Also a bit shorter delay for this demo :-)
        setTimeout(contatore.bind(null, number - 1, done), 200);
    } else {
        // when all is done: call callback
        done();
    }
}
rocketLaunch();
body { font-size: 50px; text-align: center;  }
<img id="imgRazzo" src="https://openclipart.org/download/261322/rocket-297573.svg" width="100px" height="100px"></img>
<div id="main"></div>

您可以使用 Promise构造函数,将 onFulfilled函数传递给调用 setTimeout的函数;如果number等于0调用onFulfilled解决Promise,则递归致电setTimeout,直到number等于0

var imgRazzoAcceso = {
  src: "http://placehold.it/100x100"
}
function rocketLaunch() {
  contatore(10)
  .then(function() {
    document.getElementById("imgRazzo").src = imgRazzoAcceso.src;
  })
}
function checkNumber(n) {
  return n == 0
}
function delay(number, resolve) {
  console.log("delay", number);
  setTimeout(function re() {
    if (checkNumber(number - 1)) {
      resolve()
    } else {
      delay(number - 1, resolve)
    }
  }, 1000);
}
function contatore(number) {
  return new Promise(function(resolve) {
    if (checkNumber(number)) {
      resolve();
    } else {
      delay(number - 1, resolve)
    }
  })
}
rocketLaunch()
<img id="imgRazzo" alt="imgRazzo" />

最新更新