saturation
asked on
Trouble with setTimeout and an array
I have an array of well over 30 elements, and I'm trying to do an on-screen alert of a group of 10 every 3 seconds (i.e., the first 10 elements alert one time in the first array, the next 10 elements alerted 3 seconds after that, etc.). My code below seems to be alerting the same piece of the array every time. What am I doing wrong?
function delayCode(locations2) {
var i,j,temparray,chunk = 10;
for (i=0; i < locations2.length; i+=chunk) {
temparray = locations2.slice(i, i+chunk);
setTimeout(function() {alert(temparray)}, 3000);
}
}
function delayCode(locations2) {
var i,j,temparray,chunk = 10;
for (i=0; i < locations2.length; i+=chunk) {
temparray = locations2.slice(i, i+chunk);
setTimeout(function() {alert(temparray)}, 3000);
}
}
What am I doing wrong?
You seems to think your for-loop wait the timeout before the next loop
No, it don't wait it, it just run immediately all the timers, it do this job before end of the 3000ms so when the alertS comes, the code just alert the LAST values of temparray
ASKER
This is so close, but it's not alerting the last array...i.e., if there are 26 elements in the array, it's only alerting the first two chunks and not the third. I can't seem to fix--are you able to help?
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Open in new window