在处理数组时,我需要在每个元素之后保持延迟或暂停1.5秒。
我尝试使用$.delay(1500);
并且最初也尝试使用setInterval
,但由于未定义setInterVal
,因此引发了错误。
请告诉我如何解决此错误。
function doPoll(){
$.each( symbols, function( index, value ){
setInterVal(function() {
poll(value);
}, 1500);
});
setTimeout(doPoll,3000);
}
// This is my complete code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
</title>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
var symbols = [ "AAA","BBB"];
$(document).ready(function () {
doPoll();
}
);
function doPoll(){
$.each( symbols, function( index, value ){
poll(value);
$.delay(1500);
});
setTimeout(doPoll,4000);
}
function poll(value)
{
alert('poll'+value);
}
</script>
</head>
<body>
</body>
</html>
使用pollundefined错误更新了问题(变量i未定义。)
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
</title>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
var symbols = [ "AAA","BBB"];
$(document).ready(function () {
doPoll();
}
);
var i = 0;
function doPoll() {
poll(symbols[i]);
i++;
if (i < symbols.length)
setTimeout(doPoll, 3000);
}
setTimeout(doPoll, 3000);
function poll(value)
{
alert('poll'+value);
}
</script>
</head>
<body>
</body>
</html>
答案 0 :(得分:1)
setInterval
而非setInterVal
。对于JavaScript案例而言。这正是错误消息所说的,setInterVal
未定义。
答案 1 :(得分:1)
如果您希望项目之间有延迟, 请勿使用任何类型的循环,例如for
或.each()
。
而是维护一个计数器并适当地使用setTimeout
或setInterval
。你使用它们的方式是混合的和不正确的。
以下是使用setTimeout
的示例:
var i = 0;
function doPoll() {
poll(symbols[i]);
i++;
if (i < symbols.length)
setTimeout(doPoll, 3000);
}
setTimeout(doPoll, 3000);
这是使用setInterval
:
var i = 0;
function doPoll() {
poll(symbols[i]);
i++;
if (i === symbols.length)
clearInterval(itvl);
}
var itvl = setInterval(doPoll, 3000);
答案 2 :(得分:0)
setInterval
中的大写字母V使JS寻找完全不同的(不存在的)函数。小写,你的间隔应该有效。