Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
739 views
in Technique[技术] by (71.8m points)

javascript - 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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...