gpt4 book ai didi

javascript - 无法在 for 循环中设置超时

转载 作者:可可西里 更新时间:2023-11-01 13:47:03 26 4
gpt4 key购买 nike

我正在构建一个西蒙游戏。在每一轮之后,玩家应该看到他必须在下一轮进行的 Action 。所以我创建了一个函数 showMoves 来闪烁他必须玩的方 block 。问题是该函数没有显示任何内容。谁能告诉我我错过了什么?

// the effect
function flasher(index) {
$(moves[index]).fadeIn(50).fadeOut(50).fadeIn(50).fadeOut(50).fadeIn(100);
}
var interval2;
// show the moves that supposed to be played
function showMoves() {
for (var i = 0; i < moves; i++) {
if (i === 0) {
interval2 = setTimeout(flasher(i), 1000);
} else {
interval2 = setTimeout(flasher(i), (i+1) * 1000);
}
}
}

最佳答案

setTimeout 接受一个函数作为第一个参数。我假设您通过调用 flasher 试图避免 this situation .在你的情况下,应该这样做:

  function showMoves() {
for (var i = 0; i < moves; i++) {
if (i === 0) {
interval2 = setTimeout(function(i) {return function() {flasher(i)}}(i), 1000);
} else {
interval2 = setTimeout(function(i) {return function() {flasher(i)}}(i), (i+1) * 1000);
}
}
}

关于javascript - 无法在 for 循环中设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40827762/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com