while 循环内的 setTimeout [英] setTimeout inside while loop
问题描述
我已经搜索了如何将 setTimeOut
与 for 循环一起使用,但是关于如何将它与 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);
这篇关于while 循环内的 setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!