gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:13:39 25 4
gpt4 key购买 nike

我的脚本中有这个:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com