设置超时时出现JavaScript闭合循环问题

编程入门 行业动态 更新时间:2024-10-26 23:25:04
本文介绍了设置超时时出现JavaScript闭合循环问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在教程中找到了一些示例(说这是规范示例)

I've found some example in a tutorial (said it was the canonical example)

for (var i=1; i<=5 ; i++) { setTimeout(function() { console.log("i: " + i); }, i*1000); }

现在,我了解到,闭包将当前作用域传递给该函数,并且我假定它应该输出1,2,3,4,5.但是,它会打印5次数字6.我在chrome调试器中运行它,首先它在执行循环过程中不执行i值递增的过程而没有进入函数,只有在此之后,它才进入内部函数并执行5次.我不确定为什么这样做,因为闭包将当前作用域传递给函数,但是为什么每次循环迭代时它都不执行?

Now, I understand that, closure passes in the current scope in to the function, and I assume that it should output 1,2,3,4,5. But instead, it prints number 6 five times. I ran it in the chrome debugger, and first it goes through the loop without going in to the function while doing the increment of the i value and only after that, it goes in to the inner function and execute it 5 times. I'm not sure why its doing that, I know, the current scoped is passed in to the function because of closure, but why does it not execute each time the loop iterate?

推荐答案

到超时运行时, for 循环已完成,并且 i 为6,即为什么您得到看到的输出.您需要在循环中捕获 i :

By the time the timeout runs, the for loop has finished, and i is 6, that's why you're getting the output you see. You need to capture i during the loop:

for (var i=1; i<=5 ; i++) { (function(innerI) { setTimeout(function() { console.log("i: " + innerI); }, innerI*1000); })(i); }

这会创建一个具有自己参数( innerI )的内部函数,该内部函数会立即被调用,从而捕获 i 的值以在超时时间内使用.

This creates an inner function with it's own parameter (innerI), that gets invoked immediately and so captures the value of i for use within the timeout.

更多推荐

设置超时时出现JavaScript闭合循环问题

本文发布于:2023-11-27 02:52:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1636263.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!