Javascript SetTimeout and Loops
Javascript SetTimeout and Loops
专家。Javascript没有产生所需的延迟效果
从其他问题中,我了解到,问题在于设置和我使用它的方式。但我仍然无法理解Settimeout是如何工作的。所以我把代码放在这里。由于知识的目的,只需要使用Javascript
事实上,我正在努力澄清我对javascript中的this,闭包的概念。它们是不是有点扭曲了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毫秒
以下是您可以解决的方法:
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
}
立即执行的函数创建一个保护no
值的作用域。
关于(function(no) {
:的一点解释
变量的范围是
- 全球范围
- 函数
上面的代码可能被写成
var t = 0
while (no != 500) {
(function(no2) {
t += 2000;
setTimeout(function() { size(no2,no2);} ,t);
})(no);
no += 50;
}
这里可能更清楚的是,我们有两个变量:
no
,其值随每次迭代而变化,当调用超时时为500no2
,实际上内部匿名函数的每个调用一个变量no2
每次调用内部匿名函数时,它都会声明一个新的no2
变量,该变量在调用时(在迭代期间)的值为no
。因此,该变量no2
受到保护,并由给setTimeout
的回调使用。
为什么不直接使用setInterval()?
var objImg = new Object();
var h;
var w;
var no = 100;
var myInterval = window.setInterval(function() {
size(no, no);
no = no + 50;
if (no >= 500) clearInterval(myInterval);
}, 2000);
function size(h, w) {
var objImg = document.getElementsByName('ford').item(0);
objImg.style.height = h + 'px';
objImg.style.width = w + 'px';
}
您的问题在于size()函数语法&算法:
var objImg = new Object();
var h;
var w;
var no = 100;
var int = window.setInterval(function () {
size(no,no);
no += 50;
},2000)
function size(h, w) {
if (h == 500){
window.clearInterval(int);
return;
}
var height = h + 'px';
var width = w + 'px';
document.getElementsByName('ford').item(0).style.height = height;
document.getElementsByName('ford').item(0).style.width = width;
}
http://jsfiddle.net/AQtNY/2/
相关文章:
- Selenium WebDriver and JavaScript change
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- php布尔值's小写AND大写和数字布尔值'可以接受
- setTimeout and V8
- Jquery post and onclick
- Moment js and IOS
- JavaScript Loops and JSON
- CodeAcademy: Loops and Arrays 2, 12/14
- JQuery and foreach loops
- for in and for of loops
- Javascript setTimeout, Loops and Closure
- Javascript SetTimeout and Loops