我正在尝试执行 setTimeout,我将变量传递给在 setTimeout() 中调用的函数。在一些最初的失败之后,然后使用谷歌,我找到了一个描述如何使用闭包来完成它的网站。我几乎按照示例操作,但我不断收到错误消息:
参数列表后缺少 )
此错误消息是在 setTimeout 上调用的,但据我所知,一切都已关闭。任何帮助将不胜感激:
var textureAtlas = new Image()
function init() {
textureAtlas.src = "images/textureatlast1.png";
var textureAtlasCoords = new Array("0,0", "100,0", "200,0", "300,0", "400,0", "500,0", "600,0");
var canvas = document.getElementById('textureAtlas');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
for(var c=0; c<textureAtlasCoords.length; c++) {
var thisCoord = textureAtlasCoords[c];
var thisCoordSplit = thisCoord.split(",");
var thisX = thisCoordSplit[0];
var thisY = thisCoordSplit[1];
var a = setTimeout(animate(){myFunction(ctx, textureAtlas, thisX, thisY); ctx=null, textureAtlas=null, thisX=null, thisY=null},1000);
}
} else {
alert("Looks like your browser doesn't support HTML5");
}
}
function animate() {
ctx.drawImage(thisImg,thisX,thisY, 1024, 451, 0, 0, 1024, 451);
}
最佳答案
我不完全清楚你要在这里安排什么。
我可以告诉你,setTimeout 接受一个函数字面值或一个函数引用,如下所示:
setTimeout(nameOfMyFunction, 1000); // reference -- note, NO parentheses here
setTimeout(function() { // literal -- the function being executed is "anonymous"
/* body of function here */
},
1000);
在第一种语法中,有两点很重要:
- 函数
nameOfMyFunction
必须在其他地方正常定义; - 使用此语法,您不能将任何参数传递给
nameOfMyFunction
。
如果传递一些参数很重要,那么您可以将调用包装在传递它们的匿名函数中,如下所示:
setTimeout(function() {
nameOfMyFunction(someArg, otherArg);
},
1000);
并且不清楚myFunction
的用途。 myFunction
准备供 animate
使用的绘图上下文是您的计划吗?还是应该在 animate
之前发生的其他一次性操作?
关于JavaScript 关闭错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6998965/