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);

      }
}
JavaScript

Avatar of undefined
Last Comment
Tom Beck

8/22/2022 - Mon
Tom Beck

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

leakim971

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
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?
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
SOLUTION
leakim971

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER CERTIFIED SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.