循环中的setTimeout [英] setTimeout inside while loop
问题描述
我已经在for循环中搜索了如何使用 setTimeOut
,但是对于如何在while循环中使用它并没有很多,而且我没有看看为什么反正会有很多不同。我已经写了以下代码的一些变体,但是这个循环似乎使浏览器崩溃:
I've searched for how to use setTimeOut
with for loops, but there isn't a lot on how to use it with while loops, and I don't see why there should be much difference anyway. I've written a few variations of the following code, but this loop seems to crash the browser:
while(src == '')
{
(function(){
setTimeout(function(){
src = $('#currentImage').val();
$("#img_"+imgIdx).attr('src',src);
}, 500);
});
}
为什么?
基本上我有一个动态创建的图像,其源属性有时需要加载,所以在我显示它之前,我需要继续检查它是否已加载,并且只有当它的路径在 $('#currentImage')
中可用时,我才能显示它。
Basically I have an image created dynamically whose source attribute takes time to load at times, so before I can display it, I need to keep checking whether it's loaded or not, and only when its path is available in $('#currentImage')
, then do I display it.
在我使用while循环之前,此代码工作正常,当我直接执行时
This code worked fine before I used a while loop, and when I directly did
setTimeout(function(){
src = $('#currentImage').val();
$("#img_"+imgIdx).attr('src',src);
}, 3000);
但是我不想让用户等待3秒如果加载可能会完成更快,因此我将 setTimeOut
放入while循环并缩短其间隔,以便我每半秒检查一次加载的路径。这有什么问题?
But I don't want to have to make the user wait 3 seconds if the loading might be done faster, hence I put the setTimeOut
in a while loop and shorted its interval, so that I only check for the loaded path every half second. What's wrong with that?
推荐答案
谢谢大家 - 所有的建议都有帮助。最后我使用了setInterval,如下所示:
Thanks everyone - all the suggestions helped. In the end I used setInterval as follows:
var timer;
// code generating dynamic image index and doing ajax, etc
var checker = function() {
var src = $('#currentImage').val();
if(src !== '') {
$('#img_' + imgIdx).attr('src', src);
clearInterval(timer);
}
};
timer = setInterval(checker, 500);
这篇关于循环中的setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!