Link to home
Start Free TrialLog in
Avatar of saturation
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);

      }
}
Avatar of Tom Beck
Tom Beck
Flag of United States of America image

I think the loop is long done looping before the first alert appears. By then it's on the last group of ten. Try this:
var chunk = 0;
var inerval = setInterval(function(){delayCode(locations);}, 3000);
function delayCode(locations2) {
      var step = 10;
	  if ((locations2.length-chunk) > step) {
		  alert(locations2.slice(chunk, chunk+step));
		  chunk+=step;
	  }else{
	     clearInterval(inerval);
	  }
}

Open in new window

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
Avatar of saturation
saturation

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
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial