Javascript:等待几帧后再继续功能

Javascript : Wait few frames before continue function

本文关键字:几帧 再继续 功能 等待 Javascript      更新时间:2023-09-26

我正在开发一款游戏,遇到了一些麻烦。我想要一个函数wait(frames),它将使函数在继续之前等待一些帧。

我有一个这样的主循环:

setInterval(function() {
    refreshMap();
}, 35 );

还有一个类似的函数:

function sayHello(){
    console.log("hello 1");
    wait(5);
    console.log("hello 2");
}

在执行console.log("hello 2");之前,wait(5)功能将使游戏刷新5次。有没有可能不像setTimeout()那样冻结整个游戏?

我看不出第一个和第二个函数是如何交互的。但这样的事情会让游戏等待10秒而不会冻结游戏:

setInterval(refreshMap,35);
sayHello();
function sayHello(timeToContinue) 
{
    if (!timeToContinue) //the first time it's called
    {
        console.log("hello 1");
        var nextTime = new Date();
        nextTime.setSeconds(nextTime.getSeconds() + 10);
        window.setTimeout(function(){sayHello(nextTime);}), 1); //call this function again
        return;
    }
    if (new Date() < timeToContinue) //when next the function gets here check 10 seconds have passed
    {
        window.setTimeout(function(){sayHello(timeToContinue);}), 1); //else come back later
        return;
    }
    console.log("hello 2");
}