[英]How to run a function that calls a function finished it first before calling next function. Creating a callback function
當用戶單擊任何圖像時,所有圖像 (images_holder) 都會慢慢淡出。 然后在它消失后,另一個圖像淡入,然后在 3 秒后該圖像淡出。 之后它消失了 images_holder 再次淡入。 我的問題是,在推子完成之前,secondStep 函數已經在運行。
我想要的是完成第一步並完成推子功能,然后第二步將運行。 一直在嘗試創建此回調但沒有運氣。
這是我的 html
<div id="container">
<!--<img src="images/background.jpg"/>-->
<div id="faces_holder">
<img id="face1" onclick="loadUnload(1)" src="images/face_03.png" width=350; height=656;/><img id="face2" onclick="loadUnload(2)" src="images/face_04.png" width=350; height=656;/><img id="face3" onclick="loadUnload(3)" src="images/face_05.png" width=350; height=656;/><img id="face4" onclick="loadUnload(4)" src="images/face_06.png" width=350; height=656;/><img id="face5" onclick="loadUnload(5)" src="images/face_07.png" width=350; height=656;/>
</div>
<div id="pop_face"><img id="popface_img" src=""/></div>
</div>
這是我的 JavaScript:
var id = "";
var kindface=0;
var fadeIn;
var counterValue;
var objHolder;
function loadUnload(kindface){
//FADEIN FADEOUT
function fader() {
if(fadeIn == true){
counterValue++;
//setPoint = 9;
}else{
counterValue--; // update parameters
//console.log("hit");
}
objHolder.style.opacity = "0."+counterValue // show frame
if (counterValue == setPoint){ // check finish condition
clearInterval(id);
console.log("end fader");
}
}
//FADEOUT
我剛剛添加了第三步,我將如何實現它? 我想在 secondStep 完成推子功能后運行第三步嗎?
function thirdstep() {
console.log("begin second step: ")
fadeIn = true;
counterValue = 0;
setPoint = 9;
objHolder = document.getElementById("popface_img");
objHolder.src = "images/"+ kindface +".png";
id = setInterval(fader, 100); // draw every 100ms
console.log("end second step: ")
}
function secondStep() {
console.log("begin second step: ")
fadeIn = true;
counterValue = 0;
setPoint = 9;
objHolder = document.getElementById("popface_img");
objHolder.src = "images/"+ kindface +".png";
id = setInterval(fader, 100); // draw every 100ms
console.log("end second step: ")
}
function firstStep(callback) {
console.log("begin first step: ")
fadeIn = false;
objHolder = document.getElementById("faces_holder");
counterValue = 10;
setPoint = 0;
id = setInterval(callback, 100); // draw every 100ms
console.log("end first step: ")
secondStep();
}
//RUN FIRST STEP FUNCTION
console.log("BEGIN process ")
firstStep(fader);
console.log("END OF ALL process ")
}
</script>
在你的代碼中:
> id = setInterval(callback, 100); // draw every 100ms
> console.log("end first step: ")
> secondStep();
secondStep立即被調用,它不會等待setInterval
建立的序列完成。 您需要從fader調用secondStep ,例如
function loadUnload(kindface){
[...]
function fader() {
if (counterValue == setPoint){ // check finish condition
clearInterval(id);
console.log("end fader");
// now call secondStep
secondStep();
}
}
[...]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.