jquery - 每 10 秒在 FOR 中运行一个函数

标签 jquery

我的脚本中有这个:

for(var i = 0, l = eachLine.length; i < l; i++) {
 if(eachLine[i].length>0){
  doP(eachLine[i], +i);
 }
}

用于从字符串中读取行并调用 doP 函数。 发生的情况是它太快了,导致我的网站出现一些速度问题,具体取决于文本大小。

我想要的是每10秒调用一次doP函数...换句话说,我想等待10秒再次调用doP函数...我怎样才能让它工作?

最佳答案

使用setInterval()

var i = 0, len = eachLine.length;
function looper(){
    if(i == 0)
        interval = setInterval(looper, 10000)
    if(eachLine[i].length > 0)
        doP(eachLine[i], ++i);
    if(i >= len) 
        clearInterval(interval);
}
looper();

var eachLine = ["Hi", "there", "I", "am", "lines", "of", "text"];
var i = 0, len = eachLine.length;
function looper(){
    if(i == 0)
        interval = setInterval(looper, 2000)
    if(eachLine[i].length > 0)
        doP(eachLine[i], ++i);
    if(i >= len) 
        clearInterval(interval);
}
looper();

function doP(line, count){
    $('body').append(count + ": " + line + "<br/>");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

使用setTimeout()

var i = 0, len = eachLine.length;
function looper(){
    if(eachLine[i].length > 0)
        doP(eachLine[i], ++i);
    if(i < len) 
        setTimeout(looper, 10000);
}
looper();

var eachLine = ["Hi", "there", "I", "am", "lines", "of", "text"];
var i = 0, len = eachLine.length;
function looper(){
    if(eachLine[i].length > 0)
        doP(eachLine[i], ++i);
    if(i < len) 
        setTimeout(looper, 2000);
}
looper();

function doP(line, count){
    $('body').append(count + ": " + line + "<br/>");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

关于jquery - 每 10 秒在 FOR 中运行一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35267374/

相关文章:

javascript - 如何根据数据项的属性对数据表中的复杂列进行排序?

javascript - setTimeout困惑

javascript - 至少有一个大写字母和一个数字的 jquery 或 javascript 密码生成器

javascript - Accordion + append 内容 Jquery

javascript - 当搜索字段为空时取消所有ajax请求

javascript - AJAX 请求永远不会发送。为什么?

javascript - 如何跟踪 Marionette.LayoutView 中输入的更改

javascript - 动态添加选项到 ChosenJS 选择字段,但避免添加重复项

javascript - (jQuery 到 Vanilla Javascript)固定 float 元素

javascript - "setInterval"函数正在转储构造函数中分配的属性