setTimeout inside while loop

前端 未结 3 1489
故里飘歌
故里飘歌 2020-12-18 04:41

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 dif

相关标签:
3条回答
  • 2020-12-18 05:02

    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 讨论(0)
  • 2020-12-18 05:15

    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.

    0 讨论(0)
  • 2020-12-18 05:26

    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.

    0 讨论(0)
提交回复
热议问题