Search code examples
node.jssocket.iodata-integrity

2 setInterval at different intervals modifying the same array


If i create a first setInterval that push every 1 milisecond an item in my array, and then i have another setInterval (every one second) that copy this array and reset it (the original one).

Will i be sure that i don't erase data ? since the first interval write every 1 milisecond, and the second interval reset the array every one second ?

Here is a jsfiddle http://jsfiddle.net/t1d20usr/

var data = [];

var i = 0;
var interval = setInterval(function() {

  data.push(i);
  i++;

  if(i== 10000) {
    clearInterval(interval);
  }

}, 1);

setInterval(function() {

  var recentData = data;
  //i want to be sure that this will not erase something set between the set of recentData and the reset of this array 
  data = [];   

  $('.container').append(recentData.join(',')');

}, 1000);

It works great, but due to the logic, i wonder if sometimes i could lost data.

Why am i doing this ? Because i get a lot of requests from different clients (socket emits) and i want to broadcast their request to others client only once every second instead of broadcasting on each emit from each client that is overkill. This is similar to how multiplayer game servers works. (My jsfiddle and the intervals is an example to simulate requests, i don't do it like that ! Eventually i will get emits at different intervals and will broadcast them every 30ms or something)


Solution

  • This is robust. Why? Javascript is single threaded. Each interval function runs to completion before the next one starts.

    You might consider thinking about this as a queue. Your 1ms interval function puts elements onto the queue, and your 1s function takes all the queued elements off the queue in one go.

    Your technique of replacing the data array with an empty one works well. You won't get any duplicates that way.

    If you wanted to consume one item from your data array, you could use

       const item = data.length > 0 ? data.shift() : null
    

    but that does a lot of shuffling of the elements of the array. Use your favorite search engine to find higher-performance queue implementations.