我有一個函數調用其他包含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);
}
可以使用承諾 - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise –
**它可能是一個有點難以理解** - 所以幫助大家通過提供一些簡單的代碼來幫助你。 [如何提供最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve) – iblamefish
已編輯,我希望現在可以理解我想要做什麼。 – MarioPL98