问题
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++;
});
回答1:
A few points :
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));
});
回答2:
That is so poor design, no but a total anti js pattern even beyond... Why would you define the same function over and over again!!!
$(imgNumArray).each(function (indexArraykey) {
(function (i) {
timerx[i] = setTimeout(internalCallback(i, indexArraykey), i * 500000);
})(i++);
});
function internalCallback(i, indexArraykey) {
val = indexArray[indexArraykey];
console.log("test " + i + val);
}
回答3:
I am not javascript expert, but looks like here internalCallback
is getting called instead of being passed as function to setTimeout
.
Try this:
var i = 1;
var indexArray = [3,6,9];
var timerx = new Array();
$( indexArray ).each(function( indexArraykey ) {
function internalCallback ( i, indexArraykey ) {
return function () {
val = indexArray[indexArraykey];
console.log("test " + i + val);
}
}
timerx[i] = setTimeout( internalCallback( i, indexArraykey ), i * 5000);
i++;
});
here is the fiddle http://jsfiddle.net/Guxdz/2/ (check the console log)
来源:https://stackoverflow.com/questions/15573859/jquery-settimeout-inside-each