简体   繁体   中英

How can I make javascript function to wait for other function to finish without using any external APIs?

I have a function that calls other function containing setinterval. Depending on variables, the second function needs varying amount of time to complete. If first function continues before second ends, hell happends.

The question is, how can I make first function wait for the second function to complete before proceeding with next line. I'm not allowed to use any external APIs. Thanks.

Heres the code but it may be a little hard to understand. 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);

}

I want to achieve something like this:

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); 
}

Why you didn't use callBacks?
You can pass any callBack as a function to another function, and call it whenever you want, for example, on http response or after timeOut, or in specific step of interval.

 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'); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM