JavaScript 调用异步时循环

JavaScript Loops when calling Async

问题:JavaScript可以在屏幕上成功画出几条弧线,但是在运行时它们就消失了。我正在 运行 调用 ARC 函数的简单循环,我不明白!?

我想做的就是运行 一步一步的调用和睡眠!这可以用 JavaScript 以外的任何语言轻松完成,它是一个简单的程序循环。

问题是我的图表在消失前出现了一瞬间。但是,如果我通过 JavaScript 调试器跟踪代码,它会一直工作,直到它再次消失!

沮丧!我试着用超时来包装它,这样我就可以睡觉来显示慢速动画。我的朋友们到底是怎么回事,这是 JavaScript 中的错误还是我的基础知识不存在。代码流这么写,我看不懂。

https://jsfiddle.net/nd6gktmf/

var array_length = attack_list.length;
//EDITED: declare local variables
var coordinates,
    origin_longitude,
    origin_latitude,
    dest_longitude,
    dest_latitude;

for(var i=0; i < array_length; i++) {
   coordinates = attack_list[i];
   //EDITED: consider using dot notation
   origin_longitude = coordinates.origin.longitude;
   origin_latitude = coordinates.origin.latitude;
   dest_longitude = coordinates.destination.longitude;
   dest_latitude = coordinates.destination.latitude;

   draw_arc(origin_longitude, origin_latitude, dest_longitude, dest_latitude);
}    

这只适用于调试模式!什么....

function draw_arc(origin_longitude, origin_latitude, dest_longitude, dest_latitude) {
    var data_to_map = 
        [{ 
            origin: {
                latitude: origin_latitude,
                longitude: origin_longitude
            },
            destination: {
                latitude: dest_latitude,
                longitude: dest_longitude 
            }
        }]; 

   console.log("****** Begin******");
   console.log(origin_longitude);
   console.log(origin_latitude);
   console.log(dest_longitude);
   console.log(dest_latitude);
   console.log("****** End ******");

   election.arc(data_to_map, {strokeWidth: 2});
}

如果您查看文档,似乎您必须将所有弧线放在同一个数组中。

调用 election.arc 可能会重新渲染整个图像,这就是为什么您最后只能看到最后一张的原因。

正如凯文指出的那样:删除您添加到问题中的所有 javascript 代码(当然保留您的数据:electionattack_list)并将其替换为:

// loop over the attack_list
attack_list.forEach(function(attack_item, i){
  // now attack_item is one item from the array, i is the index in the array
  // we set up a timer FOR EACH item in the array
  setTimeout(function(){
    // we make an empty array, because election.arc needs an array,
    // eventhough we'll only send 1 item in it, we wrap it in an array
    var draw_list = [];
    draw_list.push(attack_item);
    // put the item into the array
    election.arc(draw_list,{strokeWidth: 2});
  }, i*2000);
  // note: the time is i*2000ms = i*2s
  // the "1st" item in attack_list is at index 0
  // so 0*2000=0 => it'll start drawing it immediately (t=0)
  // it animates for about 1s (t=1)
  // the last drawn line is still displayed (t=1..2)
  //
  // t=2: now the timer for the "2nd" item (i=1) starts drawing
  // but because we created a new empty array and only added the 2nd item
  // into it, when it draws, it erases everything that we drew before
  // and now you only see the 2nd item is getting animated.
  // etc...
});

https://jsfiddle.net/flocsy/nd6gktmf/3/