如何在" for循环的每次迭代期间添加暂停"用Javascript?

时间:2015-09-22 18:54:19

标签: javascript

方案: 我有一系列的单词及其相应的含义,我必须在不同的DIV中间隔显示。 以下是我写的代码:

<body>
<div id="worsd">
</div>
<div id="meaning"> 
</div>
<script>
var wordss = [["word1","meaning1"],["word2","meaning2"],["word3","meaning3"]];
for(var i =0;i<wordss.length;i++)
{
var hellooo = wordss[i][0];
var hellooo1 = wordss[i][1];
document.getElementById('worsd').innerHTML = hellooo;
document.getElementById('meaning').innerHTML = hellooo1;
}
</script>
</body>

请提供有价值的指导,帮助我实现目标。

非常感谢!

3 个答案:

答案 0 :(得分:2)

您不能延迟,但您可以设置定期更新文本的计时器。

我保留了你命名的变量,但我把这个变量包装在Immediately-invoked function expression中以保持全局范围的清洁。顺便说一句,这不是必要的。

<body>
<div id="worsd">
</div>
<div id="meaning"> 
</div>
<script>
(function() // Wrap in immediately invoked function.
{
  var wordss = [["word1","meaning1"],["word2","meaning2"],["word3","meaning3"]];
  var i = 0;

  // Function that just shows the next word every time it is called.
  function nextWord() {
    var hellooo = wordss[i][0];
    var hellooo1 = wordss[i][1];
    document.getElementById('worsd').innerHTML = hellooo;
    document.getElementById('meaning').innerHTML = hellooo1;
    if (++i >= wordss.length) 
      i = 0; // Wrap when the last element is passed.
  };
  
  // Set a timer to call the function every 2 seconds.
  setInterval(nextWord, 2000);

  // Show the first word right away.
  nextWord();
})();
</script>
</body>

答案 1 :(得分:0)

var arrOfWords = [] // words here
function showWords(index) {
    // do your words display stuff here
}

var counter = 0;
var timeOut = setInterval(function(){
    counter++;
    if(counter < arrOfWords.length)
        showWords(counter)
    else
        clearInterval(timeOut)
}, 2000) // ms of loop

showWords(counter) // be sure to handle the first one

答案 2 :(得分:0)

您必须使用递归函数来执行您想要的操作。 E.g:

// timer function that loops through an array in a given interval
function timer(list, callback, time /*, onFinish, index*/ ) {
  var onFinish = arguments.length > 3 ? arguments[3] : void 0,
    index = arguments.length > 4 ? arguments[4] : 0;

  if (index < list.length) {
    callback.call(this, index, list[index]);
    list.__timed = setTimeout(function() {
      timer(list, callback, time, onFinish, ++index);
    }, time);
  } else if (onFinish) {
    onFinish.call(this);
  }

  return {
    cancel: function() {
      if (list.__timed !== void 0) {
        clearTimeout(list.__timed);
        delete list.__timed;
      }
    }
  };
}

document.addEventListener('DOMContentLoaded', function() {
  var wordss = [
      ["word1", "meaning1"],
      ["word2", "meaning2"],
      ["word3", "meaning3"]
    ];
  
  timer(wordss, function(index, item) {
    var hellooo = item[0];
    var hellooo1 = item[1];
    
    document.getElementById('worsd').innerHTML = hellooo;
    document.getElementById('meaning').innerHTML = hellooo1;
  }, 3000);
});
<body>
  <div id="worsd">
  </div>
  <div id="meaning">
  </div>
</body>

可以为任何数组调用上面的timer函数,传递一个你想要的回调函数,以及你希望在迭代之间延迟的时间。