javascript while 循环内的 setTimeout

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12996193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:35:46  来源:igfitidea点击:

setTimeout inside while loop

javascriptwhile-loopsettimeout

提问by user961627

I've searched for how to use setTimeOutwith 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:

我已经搜索了如何setTimeOut与 for 循环一起使用,但是关于如何将它与 while 循环一起使用的内容并不多,而且我不明白为什么无论如何应该有太大区别。我编写了以下代码的一些变体,但此循环似乎使浏览器崩溃:

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.

基本上我有一个动态创建的图像,其源属性有时需要时间来加载,所以在我可以显示它之前,我需要不断检查它是否已加载,并且只有当它的路径在$('#currentImage').

This code worked fine before I used a while loop, and when I directly did

这段代码在我使用 while 循环之前运行良好,当我直接使用时

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 setTimeOutin a while loop and shorted its interval, so that I only check for the loaded path every half second. What's wrong with that?

但是我不想让用户等待 3 秒,如果加载速度可能会更快,因此我把它setTimeOut放在一个 while 循环中并缩短它的间隔,这样我只每半秒检查一次加载的路径。那有什么问题?

采纳答案by user961627

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

谢谢大家 - 所有的建议都有帮助。最后我使用了 setInterval 如下:

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

回答by pdvries

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:

while 循环正在制造麻烦,就像 jrdn 指出的那样。也许你可以结合 setInterval 和 setTimeout ,一旦 src 被填充,清除间隔。我在此处放置了一些示例代码以提供帮助,但不确定它是否完全符合您的目标:

    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.

希望这可以帮助。

回答by user961627

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.

setTimeout 安排一个函数在未来的时间运行,但它不会阻塞,它只是稍后运行。因此,在您的 while 循环中,您将这些函数安排为尽可能快地运行 while 循环,因此您可能会创建大量它们。

If you actually want to check every half second, use setInterval without a loop instead.

如果您真的想每半秒检查一次,请改用不带循环的 setInterval。