在for循环随机延迟

在for循环随机延迟

本文介绍了setTimeout() - 在for循环随机延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 看到许多帖子谈论 setTimeout 和闭包,但我仍然不能传递一个简单的for循环计数器。 for(i = 0; i setTimeout(function(){ console.log(i); },Math.floor(Math.random()* 1000)); } 给予出现什么问题? > 请不要火焰,我以为我理解了 setTimeout(),但显然不是。解决方案您可以使用闭包保留对循环中 i 当前值的引用: for(i = 0; i (function(i){ setTimeout (){ console.log(i); },Math.floor(Math.random()* 1000)); })(i); //将当前值传递给自执行匿名函数} 不太可能按顺序打印数字,因为您使用了随机超时(您可以使用 i * 1000 ,而不是按升序打印数字,相隔一秒)。 p> 这是工作示例。 Seen many posts talking about setTimeout and closures but I'm still not able to pass in a simple for loop counter.for (i = 0; i < 5; i++) { setTimeout(function () { console.log(i); }, Math.floor(Math.random() * 1000));}GivesWould like to haveWhat's wrong ?Please don't flame, I thought I have understood the setTimeout() tale but apparently not. 解决方案 You can use a closure to keep a reference to the current value of i within the loop:for (i = 0; i < 5; i++) { (function(i) { setTimeout(function () { console.log(i); }, Math.floor(Math.random() * 1000)); })(i); //Pass current value into self-executing anonymous function}​However, this is unlikely to print the numbers in order since you use a random timeout (you could use i * 1000 instead to make the numbers print in ascending order, one second apart).Here's a working example. 这篇关于setTimeout() - 在for循环随机延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 17:56