[英]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. 我有一个函数调用包含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.
我不允许使用任何外部API。 Thanks.
谢谢。
Heres the code but it may be a little hard to understand. 这是代码,但可能有点难以理解。 HTML:
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: 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? 为什么不使用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. 您可以将任何callBack作为函数传递给另一个函数,并可以在任何需要的时候调用它,例如,在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'); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.