6

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?

12
  • No, settimeout takes the function as a parameter and executes it later. 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. Commented Oct 21, 2012 at 8:33
  • Ah. That too. So yeah, my answer is wrong. It's just a plain old infinite loop! Commented Oct 21, 2012 at 8:33
  • Well half wrong. They should use setInterval for this anyway. 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. Commented Oct 21, 2012 at 8:41

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

3 Comments

setInterval returns an id. When you want to stop it, use clearInterval(id);
Thanks for the explanation. I take that setInterval blocks then?
No, it doesn't block. It just schedules the function to be run repeatedly unlike setTimeout which only schedules it to run once. Since it handles calling it again for you, you don't need the loop anymore.
5

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

6 Comments

Confirm this interval is actually cleared. window.clearInterval takes an intervalID as its argument and not a function.
I thought so too... but this does work. First saw it in the second answer here: stackoverflow.com/questions/109086/…
i = 0; var fn = function(){ console.log(++i); if(i > 9) console.log('clearing'), clearInterval(fn); }; setInterval(fn, 500); goes on forever.
I put console.log("checking") right before clearInterval(checker) and it didn't go on forever.
you're absolutely right! i tried that, and I could see it was checking infinitely. I've edited my answer above based on the fix.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.