3

奇怪的概念问题。下面的数组包含三个元素。当我运行此代码时,我的意图是脚本等待两秒钟,显示警报,等待两秒钟,显示警报,等待两秒钟,然后显示最终警报。相反,它只等待两秒钟,然后连续显示所有三个警报。我一直在玩弄它一段时间,但找不到我缺少的东西。有什么建议么?

      $.each(node_array, function(index,value){
        if(value != undefined){
          setTimeout(function(){
            alert("hey")},
          2000)
        }
      });
4

2 回答 2

3

迭代时,您设置了超时,但不会停止迭代。所以所有的 setTimeout 都是同时启动的。

您需要setTimeout在用户单击警报后启动下一个:

var i=0;
function onestep(){
   alert('hey');
   var value = node_array[i];
   if (++i<node_array.length) setTimeout(onestep, 2000);
}
onestep();

示范

于 2012-12-21T19:34:29.203 回答
2

每次迭代将延迟增加 2 秒。

$.each(node_array, function(index,value){
    if(value != undefined){
        setTimeout(function(){
            alert("hey");
        },(index+1)*2000)
    }
});

setTimeout 是非阻塞的,因此代码将在延迟过去之前继续运行,导致您以相同的延迟同时触发 x 个 setTimeout,因此它们都同时完成。

于 2012-12-21T19:40:20.663 回答