我的脚本中有这个:
for(var i = 0, l = eachLine.length; i < l; i++) {
if(eachLine[i].length>0){
doP(eachLine[i], +i);
}
}
Run Code Online (Sandbox Code Playgroud)
for 从字符串中读取行并调用 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();
Run Code Online (Sandbox Code Playgroud)
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();
Run Code Online (Sandbox Code Playgroud)
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/>");
}Run Code Online (Sandbox Code Playgroud)
使用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();
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)
var i = 0, len = eachLine.length;
function looper(){
if(eachLine[i].length > 0)
doP(eachLine[i], ++i);
if(i < len)
setTimeout(looper, 10000);
}
looper();
Run Code Online (Sandbox Code Playgroud)