Javascript 蛮力2048,用setInterval变傻
这个游戏,太让人上瘾了。我需要自动播放它。我的Javascript 蛮力2048,用setInterval变傻,javascript,Javascript,这个游戏,太让人上瘾了。我需要自动播放它。我的setInterval有问题,因为它只启动了我的函数一次。谢谢你的帮助 var game = $('.game-container'); function fire(el) { var moves = [37,38,39,40] var key = moves[Math.floor(Math.random()*moves.length)]; if(document.createEventObject) {
setInterval
有问题,因为它只启动了我的函数一次。谢谢你的帮助
var game = $('.game-container');
function fire(el)
{
var moves = [37,38,39,40]
var key = moves[Math.floor(Math.random()*moves.length)];
if(document.createEventObject)
{
var eventObj = document.createEventObject();
eventObj.keyCode = key;
el.fireEvent("onkeydown", eventObj);
}else if(document.createEvent)
{
var eventObj = document.createEvent("Events");
eventObj.initEvent("keydown", true, true);
eventObj.which = key;
el.dispatchEvent(eventObj);
}
}
window.setInterval(fire(game),100);
它似乎运行了一次函数,然后我在控制台中得到:
Application Cache NoUpdate event
。您在最后一行调用fire,而不是实际设置间隔
fire(game)
不会返回任何内容,因此它不会通过setInterval
任何回调。您在最后一行调用fire,而不是实际设置间隔
fire(game)
不会返回任何内容,因此它不会通过setInterval
任何回调。
fire(game)
实际上,setInterval
将调用函数,setInterval
将永远不会执行任何函数
试一试
实际上,setInterval
将调用函数,setInterval
将永远不会执行任何函数
试一试
获取字符串或函数变量:
// string syntax (NOT RECOMMENDED)
// passes "fire(game)" to eval() every 100ms.
// executes in the global scope, which is a potential scope change. thus,
// has the potential to "lose" its reference to your `fire` and `game` variables.
setInterval("fire(game)", 100);
// function-passing syntax (PREFERRED)
// executes the [anonymous] function every 100ms.
// holds onto the in-scope `fire` and `game` objects.
setInterval(function() { fire(game); }, 100);
这样做:
setInterval(fire(game), 100);
。。。将调用fire(game)
并将返回值传递给setInterval
。如果fire(game)
返回一个函数,这将是有意义的。(或者可以是eval()
'd的string
,尽管我建议不要这样做!)接受字符串或函数变量:
// string syntax (NOT RECOMMENDED)
// passes "fire(game)" to eval() every 100ms.
// executes in the global scope, which is a potential scope change. thus,
// has the potential to "lose" its reference to your `fire` and `game` variables.
setInterval("fire(game)", 100);
// function-passing syntax (PREFERRED)
// executes the [anonymous] function every 100ms.
// holds onto the in-scope `fire` and `game` objects.
setInterval(function() { fire(game); }, 100);
这样做:
setInterval(fire(game), 100);
。。。将调用fire(game)
并将返回值传递给setInterval
。如果fire(game)
返回一个函数,这将是有意义的。(或者一个string
可能是eval()
'd,尽管我建议不要这样!)FYI将字符串传递给setInterval
使用eval
,因此不建议使用;-)@RocketHazmat更新为注意首选语法。所以<代码>开火(游戏)
不是真正的功能。这是它的回报。这不是一个函数。有点混乱。@broinjc:fire
是一个函数fire(game)
调用fire
函数,因此使用其返回值。仅供参考,将字符串传递到setInterval
使用eval
,因此不建议使用;-)@RocketHazmat更新为注意首选语法。所以<代码>开火(游戏)
不是真正的功能。这是它的回报。这不是一个函数。有点混乱。@broinjc:fire
是一个函数fire(game)
调用fire
函数,因此使用其返回值。