简体   繁体   English

$ timeout内部将循环创建无限循环

[英]$timeout inside will loop creates infinite loop

I cannot seem to get the timeout and the loop to work together. 我似乎无法让超时和循环协同工作。 If I remove the loop it works or if I remove the timeout it will work. 如果删除循环,则可以正常运行;如果删除超时,则可以正常运行。 Together I will get an infinit loop and it doesnt seem like the timeout function ever runs if its inside of the while loop. 如果在一起,我将得到一个无限循环,如果它在while循环内部,则似乎没有超时函数运行过。

Any help would be appreciated! 任何帮助,将不胜感激!

function doTask (list) {
    if (list) {
        while (list.length > 0) {  
            (function(list){
                $timeout(function() {   
                   list.splice(0, 1); 
                   console.log("timeout...") 
                }, 5000); 
            })(list); 
        }
    }
}

You should use recursion to loop. 您应该使用递归循环。 Also, you should check list.length as [] is a true value. 另外,您应该检查list.length因为[]是真实值。

 function doTask(list) { if (list.length) { setTimeout(function() { list.splice(0, 1); console.log("timeout...") doTask(list); }, 500); } } var list = [1,2,3,4,5] doTask(list); 

Your code never gives chance to run timeout function. 您的代码永远不会给您提供运行超时功能的机会。

When doTask is called it goes onto the stack for running. 调用doTask时,它将进入堆栈以运行。 Now in each loop iteration, you are registering a timeout which will be executed when this doTask finishes. 现在,在每个循环迭代中,您都将注册一个超时,该超时将在doTask完成时执行。 But you never gave chance for timeout to run hence the length of the list never decreased that's why it's running forever. 但是您永远不会给超时机会,因此列表的长度永远不会减少,这就是它永远运行的原因。

Hope this clarifies your query. 希望这可以澄清您的查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM