且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

forTime循环内的SetTimeout

更新时间:2023-10-29 23:26:22

常见的误解是

It's a common misconception that setTimeout schedules events to run relative to previously queued events. It looks like you believe that, theoretically, the following:

setTimeout(f, 100);
setTimeout(g, 100);
setTimeout(h, 100);

将导致这样的时间轴:

0ms   Start
100ms Run f()
200ms Run g()
300ms Run h()

现实是, setTimeout 中的time选项表示至少在经过这么多时间后运行此函数".从前面的示例来看,您实际上会得到类似的东西

The reality is that the time option in setTimeout means "run this function after at least this much time has passed." Going off of the previous example, you would actually get something more like

0ms   Start
100ms Run f()
101ms Run g()
102ms Run h()

要正确分配代码空间,请继续增加超时时间,而不要替换超时时间.

To space out your code correctly, keep adding to the timeout time rather than replacing it.

var time = 0;

for (var i = 1; i <= numberOfChilds; i++) {
  currentIndexClass = '.alternateimage' + i;
  currentImg = jQuery(currentIndexClass);

  // Add to the previous time
  time += parseInt(jQuery(currentIndexClass).attr("data-time"), 10);
  changeImg(i, time, currentImg);
}