Friday 19 May 2017

Use "setInterval()" a dynamic number of times, and tell when "clearInterval()" has been called for all?

For node.js, I want to check for a new state every 10 seconds. This new state will exist different systems, and there could be 1 to 4 of these systems. The new state will eventually exist on all of the systems, but they will happen at different times, and once they have all updated I want to compare the results.

A broad overview would be:

for (var i = 0; i < systems.length; i++)
{
    var interval = setInterval(function() { checkForUpdate(system[i].location); }, 10000);
}

function checkForUpdate(location)
{
    // Some code here to check if the state is updated
    if (stateUpdated)
    {
        clearInterval(interval);
    }
}

My questions:

  1. Since I don't know how many intervals I'll have to set, it is difficult to call clearInterval and pass the name (since I don't want to dynamically create variable names). Can I pass the 'interval' var to checkForUpdate so that each checkForUpdate will only clear their own interval?
  2. How can I check to see if all of the intervals are cleared? My first thought is to create a variable that keeps track of the number of intervals cleared. Then set another setInterval that checks every 10 seconds to see if all intervals have been cleared, and do my final comparison of all the results once the number of intervals cleared == systems.length. But if there is a more elegant way without essentially setting another setInterval, that would be preferred. Something like a listener?


via Kramhsiri

No comments:

Post a Comment