Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto remove elements out of an array after X minute(s) in JavaScript?

I don't know if this is a silly idea. But let's say I have an array, I keep pushing new elements to it. And I want to set up logic so that any element that exists for 5 minutes will be automatically removed from that array.

Any idea for the solution?

Note that I don't want to keep the timestamp for any element, I want them to be removed automatically.

like image 626
ken.ng Avatar asked Oct 21 '25 04:10

ken.ng


1 Answers

You can create your own array class and every time you push element you setTimeout its removal. Here we push a new element every second and they are automatically removed (without shifting the remainig elements) in 5 seconds.

class MyArray extends Array {
  push() {
    const i1 = this.length;
    const i2 = super.push(...arguments);
    setTimeout(() => {
      for (let i=i1; i<i2; i++) delete this[i];
    },5000);
    return i2;
  }
}

let a = new MyArray();
let i = 0;

let t1 = setInterval(() => { a.push(i++); console.log(a); }, 1000);
setTimeout(() => {
  clearInterval(t1);
}, 60000)
like image 190
Andrew Svietlichnyy Avatar answered Oct 22 '25 17:10

Andrew Svietlichnyy