Javascript 在for循环中使用setTimeout
我需要把这段代码放在for循环中,这样我就不必写4次,我就是不能让它工作Javascript 在for循环中使用setTimeout,javascript,settimeout,Javascript,Settimeout,我需要把这段代码放在for循环中,这样我就不必写4次,我就是不能让它工作 setTimeout( function(){ document.getElementById("square").style.left="0px"; },0); setTimeout( function(){ document.getElementById("square").style.left="100px"; },1000); setTimeout
setTimeout(
function(){
document.getElementById("square").style.left="0px";
},0);
setTimeout(
function(){
document.getElementById("square").style.left="100px";
},1000);
setTimeout(
function(){
document.getElementById("square").style.left="200px";
},2000);
setTimeout(
function(){
document.getElementById("square").style.left="300px";
},3000);
到目前为止,我的答案是
for (i = 0; i <=300; i=i+100) {
j = i*10;
setTimeout(
function (){
document.getElementById("square").style.left=i+"px";
}, j);
};
for(i=0;i给你:
var square = document.getElementById('square');
for (var i = 0; i <= 3; i++) {
setTimeout(function() {
square.style.left = i * 100 + 'px';
}, i * 1000);
}
var square=document.getElementById('square');
对于(var i=0;i这应该适合您。我认为循环不会等待setTimeout
,这是您的问题
var square = document.getElementById('square');
function changeLeftPos(i, elem) {
setTimeout(function() {
elem.style.left = i * 100 + 'px';
}, i * 1000);
}
for (var i = 0; i <= 3; i++) {
changeLeftPos(i, square);
}
var square=document.getElementById('square');
功能更改leftpos(i,elem){
setTimeout(函数(){
elem.style.left=i*100+'px';
},i*1000);
}
对于(var i=0;ivar square=document.getElementById('square');
var i=0;
函数示例()
{
square.style.left=i*100+'px';
如果(i<3){
i++;
设置超时(例如,1000);
}
}
设置超时(例如,1000);
var v=[0110020300],c;
对于(ct=0;ct来说,dhouty的解决方案不起作用的原因是,循环在异步函数中携带递增值时存在问题
var square = document.getElementById('square');
for (var i = 0; i <= 3; i++) {
(function(i){
setTimeout(function() {
square.style.left = i * 100 + 'px';
}, i * 1000);
})(i);
}
var square=document.getElementById('square');
for(var i=0;i这是因为提供给setTimeout
的匿名函数将在for循环之后运行,而与指定的时间无关
此时,函数查看的i
变量是循环结束时i
的当前变量,因为setTimeout函数在循环后执行
for
循环不会创建闭包,因为javascript中没有阻塞的作用域。要解决您的问题,您需要以下内容(或类似效果的内容):
for(i=0;i除了可能使用var
初始化j和i之外,还有什么问题吗?另外,for循环的末尾有一个冒号,它不需要。@user1102901:i
不是你认为的那样。请查看我的答案,我以前处理过这个问题。我也更新了我的,以解决这个问题。是的!这个很有效!非常感谢=
var square = document.getElementById('square');
var i=0;
function example()
{
square.style.left = i * 100 + 'px';
if (i < 3){
i++;
setTimeout(example, 1000);
}
}
setTimeout(example, 1000);
var v = [0, 100, 200, 300], c;
for (ct = 0; ct <= v.length - 1; ct++) {
setTimeout(
function () {
var vl = ct;
(function () {
document.getElementById("square").style.left = vl + "px"
}())
}
)
}
var square = document.getElementById('square');
for (var i = 0; i <= 3; i++) {
(function(i){
setTimeout(function() {
square.style.left = i * 100 + 'px';
}, i * 1000);
})(i);
}
for (i = 0; i <=300; i=i+100) {
j = i*10;
(function(val) {
setTimeout(
function (val){
document.getElementById("square").style.left=val+"px";
}, j))(i);
};