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++;
});
hjpotter92
81.1k36 gold badges148 silver badges188 bronze badges
asked Mar 22, 2013 at 15:18
user1412077
-
1Why would you define a function in a loop?kidwon– kidwon2013年03月22日 15:24:53 +00:00Commented Mar 22, 2013 at 15:24
3 Answers 3
A few points :
ihas 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));
});
answered Mar 22, 2013 at 15:19
Denys Séguret
384k90 gold badges813 silver badges780 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
hjpotter92
Using
}); to end internalCallback is wrong. =) Would result in syntax error.Denys Séguret
In fact, you changed the code after my first answer. I now think that what you really want is the new code at the end of my function.
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);
}
answered Mar 22, 2013 at 15:32
kidwon
4,5265 gold badges31 silver badges46 bronze badges
Comments
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)
answered Mar 22, 2013 at 15:40
kdabir
9,8863 gold badges49 silver badges47 bronze badges
lang-js