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

时间:2016-12-04 17:53:17

标签: javascript html dom

在我的情况下,我希望只在前一个函数完成后调用<select name="Stadium"> <?php if(!($stmt = $mysqli->prepare("SELECT id, name FROM stadiums ORDER BY name"))){ echo "Prepare failed: " . $stmt->errno . " " . $stmt->error; } if(!$stmt->execute()){ echo "Execute failed: " . $mysqli->connect_errno . " " . $mysqli->connect_error; } if(!$stmt->bind_result($stadium_id, $sname)){ echo "Bind failed: " . $mysqli->connect_errno . " " . $mysqli->connect_error; } while($stmt->fetch()){ if($sname === $stadium){ echo "<option value=\"" . $stadium_id . "\" selected>" . $sname . "</option>"; } else { echo "<option value=\"" . $stadium_id . "\">" . $sname . "</option>"; } } $stmt->close(); ?> </select> ,但它恰好相反:它首先(或同时)执行文档调用,然后功能。 在我的具体情况下,我有一个火箭和一个计数器:火箭图像必须在执行document.getElementById功能后改变。

这是我的功能:

contatore()

这是function rocketLaunch(){ contatore(10); document.getElementById("imgRazzo").src = imgRazzoAcceso.src; } 函数,使用contatore

setTimeout

3 个答案:

答案 0 :(得分:1)

使用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的语法取自this链接

答案 1 :(得分:1)

我敢打赌你的函数中有一些超时/间隔/ 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()

答案 2 :(得分:0)

你可以用回调来做到这一点:

// 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>