Skip to content Skip to sidebar Skip to footer

Settimeout Inside While Loop

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 wr

Solution 1:

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.

Solution 2:

Thanks everyone - all the suggestions helped. In the end I used setInterval as follows:

var timer;
// code generating dynamic image index and doing ajax, etcvar checker = function() {
    var src = $('#currentImage').val();
    if(src !== '') {
    $('#img_' + imgIdx).attr('src', src);
        clearInterval(timer);
    }
};

timer = setInterval(checker, 500);  

Post a Comment for "Settimeout Inside While Loop"