最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - setTimeout inside while loop - Stack Overflow

programmeradmin3浏览0评论

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);
     });
} 

Why?

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.

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);

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?

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);
     });
} 

Why?

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.

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);

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?

Share Improve this question edited Feb 25, 2017 at 10:06 H. Pauwelyn 14.3k28 gold badges91 silver badges160 bronze badges asked Oct 21, 2012 at 8:27 user961627user961627 12.7k43 gold badges148 silver badges211 bronze badges 12
  • No, settimeout takes the function as a parameter and executes it later. – user462356 Commented Oct 21, 2012 at 8:32
  • @jrdn I am not talking about the one inside setTimeout, I am talking about the one outside. BTW that function declaration is not needed actually. – Alvin Wong Commented Oct 21, 2012 at 8:33
  • Ah. That too. So yeah, my answer is wrong. It's just a plain old infinite loop! – user462356 Commented Oct 21, 2012 at 8:33
  • Well half wrong. They should use setInterval for this anyway. – user462356 Commented Oct 21, 2012 at 8:34
  • 1 @AlvinWong or, as it's an image, hook its .onload handler, which was designed precisely to allow you to tell when an image finished loading. – Alnitak Commented Oct 21, 2012 at 8:41
 |  Show 7 more comments

3 Answers 3

Reset to default 10

The while loop is creating trouble, like jrdn is pointing out. Perhaps you can combine both the setInterval and setTimeout and once the src is filled, clear the interval. I placed some sample code here to help, but am not sure if it completely fits your goal:

    var src = '';
    var intervalId = window.setInterval(
        function () {

            if (src == '') {
                setTimeout(function () {
                    //src = $('#currentImage').val();
                    //$("#img_" + imgIdx).attr('src', src);
                    src = 'filled';
                    console.log('Changing source...');
                    clearInterval(intervalId);
                }, 500);
            }
            console.log('on interval...');
        }, 100);

    console.log('stopped checking.');

Hope this helps.

The problem is probably that you're not checking every half second.

setTimeout schedules a function to run at a future time, but it doesn't block, it just runs later. So, in your while loop you're scheduling those functions to run just as fast as it can iterate through the while loop, so you're probably creating tons of them.

If you actually want to check every half second, use setInterval without a loop instead.

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);  
发布评论

评论列表(0)

  1. 暂无评论