Javascript SetTimeout和循环 [英] Javascript SetTimeout and Loops
问题描述
专家。
Javascript没有产生所需的延迟效果。
从其他问题来看,我知道了,问题在于settimeout和我使用它的方式。
但我仍然无法理解,Settimeout的工作原理。
所以我在这里放代码。
由于知识目的,仅需要使用Javascript。
实际上我试图在javascript中清除关于 this,closure 的概念。
它们是Javascript的扭曲之物吗?
Experts.
Javascript not producing desired delay effect.
From other questions, on SO I got to know that, problem is with settimeout and the way I am using it.
But still I am not able to comprehend, how Settimeout works.
So I am putting code here.
Need to use Javascript only, because of knowledge purpose.
Actually I am trying to clear my concepts about this, closure in javascript.
Are they kind of twisted things of Javascript?
var objImg = new Object();
var h;
var w;
var no = 100;
while (no != 500) {
setTimeout(function () {
size(no, no);
}, 2000);
/* it's get executed once, instead of repeating with while loop
Does it leave loop in mid? I get image with 500px height and
width, but effect is not acheived.
*/
no = no + 50;
}
function size(h, w) {
var objImg = document.getElementsByName('ford').item(0);
objImg.style.height = h + 'px';
objImg.style.width = w + 'px';
}
推荐答案
你有两个问题:
-
no
将在调用回调时具有循环结束的值 - 你在同一时间编程所有超时2000毫秒,循环运行的时间。
no
will have the value of end of loop when the callback is called- you're programming all your timeouts 2000 ms from the same time, the time the loop run.
以下是你如何解决这个问题:
Here's how you could fix that :
var t = 0
while (no != 500) {
(function(no) {
t += 2000;
setTimeout(function() { size(no,no);} ,t);
})(no);
no = no+50; // could be written no += 50
}
立即执行的函数创建一个范围它保护没有
的价值。
The immediately executed function creates a scope which protects the value of no
.
关于(function(no){
:
变量的范围是
- 全球范围
- 一个函数
上面的代码可以写成
var t = 0
while (no != 500) {
(function(no2) {
t += 2000;
setTimeout(function() { size(no2,no2);} ,t);
})(no);
no += 50;
}
这里可能更清楚我们有两个变量:
Here it's probably more clear that we have two variables :
-
no
,其值随每次迭代而变化,是调用超时时500; -
no2
,实际上是一个变量no2
每次调用内部匿名函数
no
, whose value changes with each iteration and is 500 when the timeouts are calledno2
, in fact one variableno2
per call of the inner anonymous function
每次调用内部匿名函数时,它都会声明一个新的 no2
变量,其值为 no
在通话时(迭代期间)。此变量 no2
因此受到保护,并由给予 setTimeout
的回调使用。
Each time the inner anonymous function is called, it declares a new no2
variable, whose value is no
at the time of call (during iteration). This variable no2
is thus protected and is used by the callback given to setTimeout
.
这篇关于Javascript SetTimeout和循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!