使用计时器连续遍历数组

时间:2018-08-09 13:50:37

标签: css angular typescript loops

这个想法是要在从API接收到的两个对象的图像属性之间交替显示,并在对象中显示图片一段确定的时间,然后连续遍历整个数组。 (狗显示30秒钟,然后猫显示10秒钟并重复序列)。

    "data": [
        { 
            "title": "Example",
            "content": [
                {
                  "FirstPart": {
                    "img": "dog.jpg",
                    "duration": "30"
                  }
                },
                {
                  "SecondPart": {
                    "img": "cat.jpg",
                    "duration": "10"
                  }
                }
            ]
      }

这是我的尝试:

    getInfo() {
      let duration: number;
      let imgText: string;

      const content = data['content'];
      for (const part of content) {
        startCountdown(part.duration);
      }
    }

    startCountdown (seconds: number) {  
       let counter = seconds;
       const intv = setInterval(() => {
          console.log(counter);
          counter--;

             if (counter < 0 ) {
                clearInterval(intv);
                console.log('Ding!'); // This should be where I put my image
             }}, 1000);}

这是我的两个问题:

  1. 此解决方案同时为两个对象启动计时器。我该如何控制它,以便第一个计时器结束时下一个计时器开始计时?

  2. 如果我想再次遍历数组,由于循环永无休止,我的浏览器开始崩溃。我不知道怎么做才能遍历数组,即使我知道这是错误的。我该如何解决这个问题?

    // Instead of looping the over the array once like stated above
      for (const part of content) { 
        startCountdown(part.duration);
      }
    
    // I would of tried to re run the loop 
      for (let i = 0; i < content.length; i ++) {
         if (i === content.length) { 
            i = 0 ;
         }
         <-- There was a whole bloc of code I had inserted here in my original code 
         but it just never worked because of my for loop above -->//
      }
    

1 个答案:

答案 0 :(得分:2)

您可以使用setTimeout代替setInterval并在处理程序的末尾调用它:

const content = [
  { "img": "dog.jpg", "duration": "2" },
  { "img": "cat.jpg", "duration": "5" },
  { "img": "bird.jpg", "duration": "3" },
  { "img": "horse.jpg", "duration": "1" },
];

startCountdown(content, 0);

function startCountdown(content, index) {
  console.log('show!', index, content[index]);

  setTimeout(() => {
    startCountdown(content, (index + 1) % content.length);
  }, content[index].duration * 1000);
}

请注意,我确实简化了您的对象。