每个内部的jquery setTimeout [英] jquery setTimeout inside each
本文介绍了每个内部的jquery setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些与此类似的代码,可以在某些图像中移动...虽然可以,但是似乎不尊重计时器
i have some code similar to this, that moves inside some images... it works but it doesn't seem to respect timer
var i = 1;
var indexArray = array(1,2,3);
var timerx = new Array();
$( indexArray ).each(function( indexArraykey ) {
function internalCallback ( i, indexArraykey ) {
val = indexArray[indexArraykey];
console.log("test " + i + val);
});
timerx[i] = setTimeout( internalCallback( i, indexArraykey ), i * 500000 );
i++;
});
推荐答案
几点:
-
i
在调用回调时具有循环结束的值. - 要使用jQuery遍历数组,请使用
$.each(array,
而不是$(array).each(
- 该函数不必在循环中定义
- 每个都将索引作为回调的第二个参数,并将值作为第一个参数.
i
has the value of end of loop by the time the callback is called.- to iterate over an array using jQuery, use
$.each(array,
, not$(array).each(
- the function doesn't have to be defined in the loop
- each gives the index as second argument of the callback and as first argument the value.
所以看来您想要的实际上是这样的:
So it seems that what you want is in fact this :
var indexArray = array(1,2,3);
var timerx = [];
$.each(indexArray, function( indexArrayValue, i ) {
timerx.push(setTimeout(function(){
console.log("test " + i + ' : ' + indexArrayValue);
}, (i+1) * 500000));
});
这篇关于每个内部的jquery setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文