为什么我的setInterval函数只被调用一次
Why is my setInterval function only being called once?
我有一个对象/函数,它开始于
function Game ( board, numBlocks ) {
// ...
this.speedMap = { "fast": 100, "medium": 300, "slow": 600 };
this.curSpeed;
this.mover; // the setInterval(...) function that causes the snake's movement
// This is set when a game is instantiated with startNew(...)
// ...
this.Snake = function ( game )
{
this.createNew = function ( )
{
// ...
}
this.move = function ( )
{
console.log("The move() function got called!"); // test
}
}
// ...
this.startNew = function ( spd ) {
// ...
this.snake = new this.Snake(this);
this.snake.createNew();
// ...
this.curSpeed = spd;
this.mover = setInterval(this.snake.move(), this.speedMap[this.curSpeed]);
}
(为了简单起见,我已经注释掉了所有不应该与我的问题相关的代码)
由于某些原因,我附加到setInterval
的函数只在我实例化带有
SG = new Game(snakeBoard, 16);
SG.startNew("medium");
它应该每300
毫秒被调用一次。
完整Javascript: https://github.com/jamkin/Snake/blob/master/SnakeGame/Scripts/game.js
查看上面示例中的JS控制台,并查看
move()函数被调用了!
只打印一次。
我在这里错过了什么?
奖金问题:
在面向对象的Javascript中创建一个静态对象/函数的等效是什么?具体地说,
this.speedMap = { "fast": 100, "medium": 300, "slow": 600 };
在我的对象是相同的每一个这样的对象被实例化,所以它应该是const static
或任何JS等效的
Replace:
this.snake.move()
:
this.snake.move
所以,你有:
this.mover = setInterval(this.snake.move, this.speedMap[this.curSpeed]);
setInterval
的第一个参数是一个函数。你不应该叫它。
您的代码正在做的是将响应从this.snake.move()
传递到setInterval
相关文章:
- 如何用JavaScriptEasy的方式一次调用大量restful服务
- 有没有一种方法可以在一次调用中修改每个jquery对象的特定属性
- 如何在一次调用中使用jquery从外部文件中获取多个剑道ui模板
- JS - 正则表达式替换在一次调用中发生多次,如何让它运行一次
- 进度条函数在一次调用后中断
- 如何使用上一次调用的数据进行第二次 JS .post 调用
- 如何通过一次调用 Facebook Graph API 来获取多个相册图片 URL
- 创建不会中断上一次调用的重复动画
- 如何只需一次调用就可以将对象数组保存到mongoose DB中
- 为什么函数只运行一次?在上一次调用完成后,尝试使用计数器函数多次运行函数
- 如何在android中一次调用多个java脚本函数来加载webview
- 下划线throttle+确保最后一次调用
- 如何重复调用一个函数并等待下一次调用之前完成
- 如何从函数的最后一次调用中判断它是同步调用还是异步调用?
- 我有这三个函数,该怎么做呢在onload时一个接一个地调用它们在refresh时一次调用一个函数
- 函数只适用于最后一次调用
- 一次调用两个函数
- 在Symfony 2上使用Assetic组合文件,只对所有CSS文件进行一次调用
- 烬:每5秒轮询一次api,但要在获得前一次调用的响应之后
- 一次调用多个ajax函数,PHP, ajax