javascript - 带有循环的 jQuery 中的 setTimeout

标签 javascript jquery settimeout

我有一个单词数组,我想按延迟顺序将 div 标记更改为每个单词。

<script>
    function printWord(w) {
    setTimeout(function() {
        $("#word").text(w);
        }, 1000);

     }

function readBook() {
    var array = $("#offscreen_text").text().toString().split(/[\s\n]+/);
    for (i =1; i < array.length; i++){
        printWord(array[i]);
    }

}
</script>
<body onload="readBook()">
<div id="word"></div>
<div id="offscreen_text">hi hello bye goodbye this is a test with some random text</div>
</body>

当我运行 readBook() 时,似乎什么都没有发生。

最佳答案

您可以在不使用 for 循环的情况下使用 setInterval。

function readBook() {
    var array = $("#offscreen_text").text().toString().split(/[\s\n]+/);
    var i=0;
    setInterval(function(){
        $("#word").text(array[i]); i++;    
    },1000);   
}

演示:http://jsfiddle.net/sywzno5p/

使用 clearInterval() 编辑 Fiddle:http://jsfiddle.net/gn6eh7t1/

关于javascript - 带有循环的 jQuery 中的 setTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28534470/

相关文章:

javascript - 如何垂直显示 <h1> 元素(每个字符换行)

javascript - jQuery 在重置后保留克隆行数

jquery - 带有scroll.depth.js的Google跟踪代码管理器

javascript - javascript中不同数据类型的数组

javascript - 传递给 setTimeout 的函数 fn 是否不是作为函数调用,而是作为类似 window.fn() 的方法调用?

javascript - 如何确定 setTimeout 是否在后台运行

javascript - 为什么人们说 javascript eval() 是邪恶的,但您却没有反对 setTimeout 和 setInterval 等?

javascript - FireFox 键盘事件按钮

javascript - 将成功添加到双 jquery/ajax post

javascript - 云函数问题,查询生成数组?