[英]Delay javascript code execution inside for loop
I have the following for loop: 我有以下for循环:
for (var i = tileLog.length - 1; i >= 0; i--) {
$('.' + tileLog[i]).mouseenter();
};
1 < tileLog.legth < 1025 1 <tileLog.legth <1025
Is there a way to delay each iteration of the loop so that mouseenter() is triggered every x miliseconds? 有没有一种方法可以延迟循环的每次迭代,以便每隔x毫秒触发一次mouseenter()?
I have tried: 我努力了:
function doSetTimeout(i) {
setTimeout(function() { $('.' + i).mouseenter(); }, 250);
}
for (var i = tileLog.length - 1; i >= 0; i--)
doSetTimeout(tileLog[i]);
This doesn't seem to work, it just delays by 250ms then iterates through the loop 这似乎不起作用,只是延迟了250毫秒,然后遍历循环
As an alternative to using setTimeout()
you could also use setInterval()
. 作为使用setTimeout()
的替代方法,您还可以使用setInterval()
。
Define a running variable in the outer scope (like your running i
in the loop). 在外部范围内定义一个运行变量(例如您在循环中运行i
)。 In each iteration, besides calling your function, decrement the running variable. 在每次迭代中,除了调用函数外,还要减小运行变量。 If it is below zero, stop the setInterval()`` : 如果它小于零,则停止setInterval()``:
var index = tileLog.length - 1,
timer = setInterval( function(){
$('.' + tileLog[index]).mouseenter();
index -= 1;
if ( index < 0 ) {
clearInterval( timer );
}
}, 250 );
There is no actual sleep()
function or something similar. 没有实际的sleep()
函数或类似的东西。 Would also be problematic as JavaScript (for most cases) is single threaded and such a method would block the render thread, thus rendering your browser inaccessible. 由于JavaScript(在大多数情况下)是单线程的,并且这样的方法会阻塞渲染线程,从而使您的浏览器无法访问,因此也会出现问题。
There is no sleep or such in JavaScript. JavaScript中没有睡眠等。 So your approach with timeout is correct. 因此,您的超时方法是正确的。
var tileLog;
var i = titleLog.length - 1;
function func1() {
$('.' + tileLog[i]).mouseenter();
if (--i) {
window.setTimeout(func1, 250);
}
}
// and of course start the process
func1();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.