2017-01-22 8 views
0

我有一個函數調用其他包含setinterval的函數。根據變量,第二個函數需要不同的時間才能完成。如果第二個功能在第二個功能結束之前繼續,那麼發生了。如何讓javascript函數等待其他函數完成而不使用任何外部API?

問題是,如何使第一個函數在繼續下一行之前等待第二個函數完成。我不允許使用任何外部API。謝謝。

繼承人的代碼,但它可能有點難以理解。 HTML:

<html> 
<head> 
<style> 
#canvas { 
background-color: rgba(158, 167, 184, 0.2); } 
</style> 

</head> 
<body onload="room1();"> 
    <canvas id="canvas" style="border: none;" width="800" height="600"></canvas>  
<script src="main.js"></script> 
</body> 
</html> 

JS:

var canvas=document.getElementById("canvas"); 
var gra=canvas.getContext("2d"); 
gra.font = "20px Courier New"; 

function pisz(text,x,y, interval) { 
x1=x; 
var i=0; 
var stopPisz=setInterval(function(){ 
if (i<text.length) { 
    var audio = new Audio('typwriter.wav'); 
    audio.volume=.1; 
    if (i%3==0 && text[i]!=" ") audio.play(); 
    gra.fillText(text[i],x1,y); 
    x1=x1+12; 
    if (x1>700 && text[i]==" "){ 
     x1=x; 
     y=y+22; 
     } 
    } 
    if (i>text.length-2) clearInterval(stopPisz); 
    i++; 
    },interval); 
} 


function room1() { 
text1="Witam cię w mojej grze. Twoim zadaniem jest rozwiązanie zagadek i wydostanie się z labiryntu pokoji."; 
text1.split(""); 
pisz(text1,20,30,50); 


text2="gfhfdghd hg fdhfgdfdf fdhfdgdfdf hdgdfhdfgdfghd"; 
text2.split(""); 
pisz(text2,20,200,50); 

} 

我要實現的是這樣的:

function f1() { 

function f2(/*some parameters*/); 
//wait for function f2 to end, then proceed to next line of this function 

function f2(/*some parameters*/); 
//wait, etc. 

} 

function f2(/*some parameters*/){ 
//doing something once 
setInterval(function(/*some parameters*/){ 
//repeating something for some time, then clearInterval so the function ends 
    },some interval); 
} 
+3

可以使用承諾 - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise –

+1

**它可能是一個有點難以理解** - 所以幫助大家通過提供一些簡單的代碼來幫助你。 [如何提供最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve) – iblamefish

+0

已編輯,我希望現在可以理解我想要做什麼。 – MarioPL98

回答

2

爲什麼你沒有使用回調?
您可以將任何回調函數作爲函數傳遞給另一個函數,並隨時調用它,例如,在http響應或timeOut之後,或在特定的時間間隔內調用它。

var f1 = function(delay, cb) { 
 
    setInterval(function() { 
 
    // do whatever you want, and now it's time to call your second function 
 
    if (cb) cb(); 
 
    }, delay); 
 
} 
 

 
var f2 = function(param) { 
 
    console.log('second function', param || '---'); 
 
} 
 

 

 
// Use like this: 
 

 
f1(1000, f2); 
 

 
// or : 
 

 
f1(2000, function() { 
 
    console.log('second function will be call'); 
 
    f2('with param'); 
 
});

+0

這個答案需要更多解釋。 – Soviut

+0

@Soviut檢查更新。 –

+0

檢查我的問題,我添加了簡化的代碼。 – MarioPL98

相關問題