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?

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
user961627
  • 12,379
  • 42
  • 136
  • 210
  • No, settimeout takes the function as a parameter and executes it later. –  Oct 21 '12 at 08: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 Oct 21 '12 at 08:33
  • Ah. That too. So yeah, my answer is wrong. It's just a plain old infinite loop! –  Oct 21 '12 at 08:33
  • Well half wrong. They should use setInterval for this anyway. –  Oct 21 '12 at 08:34
  • What are you trying to do, actually? – Alvin Wong Oct 21 '12 at 08:35
  • if my variable ``src`` is empty, i want to check, every half second, whether $('#currentImage') now has a value in it or not. when it does, i want to stop looping, and fill ``src`` with its value. – user961627 Oct 21 '12 at 08:36
  • You probably want to bind to the `$('#currentImage').change(function(){ /*...*/ })` instead of checking it from time to time. – Alvin Wong Oct 21 '12 at 08:37
  • 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 Oct 21 '12 at 08:41
  • thanks, but it's a dynamic image... it doesn't load of its own accord - I have to let it know what it's "src" should be. I can only give it its source once the hidden input $('#currentImage') is populated, but I cannot use the ``change`` handler for $('#currentImage') either for the same reason - a lot of dynamic images being created on the fly. – user961627 Oct 21 '12 at 08:57
  • @user961627 so what's populating that hidden input? Elements don't just change of their own accord - there'll be _some_ sort of event on `#currentImage` or _some_ function that populated it. – Alnitak Oct 21 '12 at 09:07
  • well okay i'll tell you although it's getting really involved.. The hidden input gets populated by an ajax query that a user requests - but ajax is asynchronous and the dynamic image is not created immediately after the ajax query, but after the user hits an 'OK' button. So only when they hit OK do I populate the image - and by the time they hit 'OK', sometimes the ajax has loaded, and sometimes it hasn't, so that's why I have to check at short intervals. – user961627 Oct 21 '12 at 09:15
  • possible duplicate of [How do I add a delay in a JavaScript loop?](http://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop) – Chris Moschini Jul 25 '13 at 22:11

3 Answers3

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.

pdvries
  • 1,372
  • 2
  • 9
  • 18
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.

  • setInterval returns an id. When you want to stop it, use clearInterval(id); –  Oct 21 '12 at 08:43
  • Thanks for the explanation. I take that setInterval blocks then? – user961627 Oct 21 '12 at 09:31
  • 2
    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. –  Oct 21 '12 at 09:33
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);  
WheretheresaWill
  • 5,882
  • 7
  • 30
  • 43
user961627
  • 12,379
  • 42
  • 136
  • 210
  • Confirm this interval is actually cleared. [`window.clearInterval`](https://developer.mozilla.org/en-US/docs/DOM/window.clearInterval) takes an `intervalID` as its argument and not a _function_. – Paul S. Oct 21 '12 at 09:53
  • I thought so too... but this does work. First saw it in the second answer here: http://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript – user961627 Oct 21 '12 at 11:30
  • `i = 0; var fn = function(){ console.log(++i); if(i > 9) console.log('clearing'), clearInterval(fn); }; setInterval(fn, 500);` goes on forever. – Paul S. Oct 21 '12 at 15:04
  • I put ``console.log("checking")`` right before ``clearInterval(checker)`` and it didn't go on forever. – user961627 Oct 22 '12 at 06:48
  • That is because `src` isn't `''` anymore. Put the log before the _if_. – Paul S. Oct 22 '12 at 13:15
  • 1
    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. – user961627 Oct 22 '12 at 13:23