0

I need help creating a function that gonna return me 3 elements from an array each time with time interval of 3 seconds. Let say I have an array

const Array = [{name:'A'},{name:'B'},{name:'C'},{name:'D'},{name:'E'},{name:'F'},{name:'G'},{name:'H'},{name:'I'}];

It should return array like

 [{name:'A'},{name:'B'},{name:'C'}] 

then after 3 seconds it should return array

 [{name:'D'},{name:'E'},{name:'F'}]

And so on also when the arrays gets end repeat the loop again.

I tried using chunk where i used slice and filter but that just return me an array of chunks together.

Thanks so much

2
  • What have you tried? Where did it go wrong? Commented Jun 8, 2017 at 22:38
  • A function cannot return multiple things at different times. What exactly are you looking for? Do you want to use a callback? Commented Jun 8, 2017 at 23:19

2 Answers 2

2

You can do this with a generator:

// Takes an array and the of the slice/subarray
function* subArray(array, size) {
  let i = 0;
  let remaining = true;
  while (remaining) {
    yield array.slice(i, i + size);
    i += size;
    if (i >= array.length) {
      remaining = false;
    }
  }
}

// Takes an array, a subarray size, and an interval in seconds
const getSubArraysAtInterval = (array, size, seconds) => {
  const iter = subArray(array, size);
  const interval = setInterval(() => {
    const next = iter.next();
    if (next.done) {
      clearInterval(interval);
      console.log('No values remaining');
    } else {
      console.log(next.value);
    }
  }, seconds * 1000)
}

getSubArraysAtInterval([1, 2, 3, 4, 5, 6], 3, 3);

Working fiddle: https://jsfiddle.net/adrice727/msx3sf03/1/

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, that looks really good. How about the looping? I just want to get it started again from first element when ends.
1
const array = [{name:'A'},{name:'B'},{name:'C'},{name:'D'},{name:'E'},
{name:'F'},{name:'G'},{name:'H'},{name:'I'}];

let i = 0
setInterval(() => {
  console.log(array.slice(i,i+3))
  i*3 > array.length ? i=0 : i += 3
}, 3000)

The jsbin: https://jsbin.com/yoqelu/edit?html,js,console,output

2 Comments

It seems to me that i*3 is increasing geometrically but i += 3 is increasing linearly.
That is the check for the end of the array, in which case the counter is reset. I added a jsbin to the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.