gpt4 book ai didi

javascript - 如何让 javascript 函数等待其他函数完成而不使用任何外部 API?

转载 作者:行者123 更新时间:2023-12-01 04:06:21 31 4
gpt4 key购买 nike

我有一个函数调用其他包含 setinterval 的函数。根据变量的不同,第二个函数需要不同的时间才能完成。如果第一个函数在第二个函数结束之前继续,就会发生 hell 。

问题是,如何让第一个函数等待第二个函数完成后再继续下一行。我不允许使用任何外部 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);
}

最佳答案

为什么不使用回调?
您可以将任何回调作为函数传递给另一个函数,并在需要时调用它,例如,在 http 响应时或超时后,或在间隔的特定步骤中。

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

关于javascript - 如何让 javascript 函数等待其他函数完成而不使用任何外部 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41796467/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com