setInterval时间未获得正确的值

时间:2019-06-19 09:40:38

标签: javascript jquery

我有两个数组。我想将其中一个文件和另一个文件显示在iframe中。我遍历它们,文件正确显示,但时间始终设置为第一个元素。

iframe始终加载10000毫秒。

$(function() {
  var urls = ['/uploads/presentations/1560837902.pdf', '/uploads/presentations/1560837925.mp4', '/uploads/presentations/1560837959.jpg', '/uploads/presentations/1560838138.docx', '/uploads/presentations/1560838215.ppt'];
  var time = [10000, 40000, 10000, 20000, 10000];
  var i = 0;

  function loadIframe(url) {
    $('#iframe').attr('src', url);
  }

  setInterval(function() {
    // update the index
    i = (i + 1) % urls.length;
    loadIframe(urls[i]);
  }, time[i]);

  loadIframe(urls[i]);
});

1 个答案:

答案 0 :(得分:4)

问题是因为您仅定义了一个间隔,因此延迟始终相同。

要解决此问题,您可以改用递归超时,在前一个触发时定义下一个超时。试试这个:

$(function() {
  var urls = ['/uploads/presentations/1560837902.pdf', '/uploads/presentations/1560837925.mp4', '/uploads/presentations/1560837959.jpg', '/uploads/presentations/1560838138.docx', '/uploads/presentations/1560838215.ppt'];
  var time = [10000, 40000, 10000, 20000, 10000];

  function loadIframe(i = 0) {
    $('#iframe').attr('src', urls[i % urls.length]);
    console.log(`Changing src to ${urls[i % urls.length]}`);
    
    setTimeout(function() {
      loadIframe(++i);
    }, time[i % time.length]);
  }

  loadIframe();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>