for循环中的setTimeOut

时间:2016-08-25 17:47:02

标签: javascript jquery settimeout

我对如何在for循环中使用setTimeout函数感到困惑。我想要做的是根据数组一次突出显示一个div。这是我的代码:

for (i = 0; i < strArray.length; i++) {
  doSetTimeout(i, colors, strArray);
}

然后是函数doSetTimeout:

function doSetTimeout(i, colors, strArray) {
  $("use." + strArray[i]).css("fill", colors[Math.floor((Math.random() * colors.length) + 1)]);
  setTimeout(function() {
    $("use").css("fill", "#333333");
  }, 1000);
}

基于this thread,我认为有一个单独的功能可以解决问题,但我仍然遇到一个问题,即所有的div同时闪烁。任何人都知道问题可能是什么?还有另一种,更好的方法吗?

3 个答案:

答案 0 :(得分:4)

你可以这样做:

TypeError: /var/www/.../es6/app.js: Duplicate declaration "stream"
> 31 | import stream from './routes/stream';

这会创建一个函数并立即为数组中的第一个元素执行它。

所有其他调用仅在触发上一个超时事件时完成,这将确保顺序处理。

当所有元素都被处理时,整个事情就结束了,因为在最后一次调用(function doSetTimeout(i, colors, strArray) { if (i >= strArray.length) return; // nothing more to do $("use." + strArray[i]).css("fill", colors[Math.floor((Math.random() * colors.length) + 1)]); setTimeout(function() { $("use").css("fill", "#333333"); // call the function recursively doSetTimeout(i+1, colors, strArray); }, 1000); })(0, colors, strArray); // Execute immediately for index 0 时没有安排新的超时。

答案 1 :(得分:0)

为什么不使用setInterval?

SKNode

答案 2 :(得分:0)

你可以这样做:

<select id="select2" name="field">
    <option value="1" selected>title 1</option>
    <option value="2" selected>title 2</option>
</select>