具有更改参数的 JavaScript 睡眠函数

javascript sleep function with changing parameters

本文关键字:JavaScript 函数 参数      更新时间:2023-09-26

数组移动只包含我想在画布上绘制的几个移动。 基本上是一个 deltaTime to 睡眠和一个绘制命令。

这根本行不通:(

for (var i=0; i< parsed.moves.length; i++)
{
    var e = parsed.moves[i];
    setTimeout(function(){drawCmd(context,e)}, e.deltaTime*1000);
    //deltaTime are values btn 0-1, the sleep time i need to set btw commands 
 }  

function drawCmd(canvasctx, e)
{   
switch(e.type)
{
   //case ...
}
 }

它什么也没做,甚至没有调用drawCmd函数

您的代码仅通过e.deltaTime*1000延迟所有drawCmd,然后一次执行所有i = 10

如果你的意思是"画画和等待,画画和等待",试试这个:

(function loop(i){
    var e = parsed.moves[i];      //e at current "i"
    if(i< parsed.moves.length){   //if not equal to length
        setTimeout(function(){
            drawCmd(context,e);   //draw in e.deltaTime*1000 milliseconds
            loop(++i);            //loop again
        }, e.deltaTime*1000);
    }
}(0));                            //start with i=0
您可能

想要检查 deltaTime 的数据类型

    setTimeout(function () { }, undefined * 1000); // <- Executes imidiately
    setTimeout(function () { }, '1' * 1000); // <- Executes after 1 second
    setTimeout(function () { }, 1 * 1000); // <- Executes after 1 second
    setTimeout(function () { }, new Date() * 1000); // <- Executes after a long (i.e. 1337852997592 seconds) time