Design & Download
Your JS Library
in Seconds!!!

Snippet: on0() - Determine When Multiple Asynchronous Calls Are Done

Written by Christopher West (cwest) on May 14, 2017.
Can be used to determine when multiple asynchronous calls are finished.
function on0(callback, opt_initial) {
  var positiveCallCount = 0, value = opt_initial || 0;
  return function(increment) {
    increment = ('boolean' == typeof increment || increment === undefined) ? increment ? 1 : -1 : +increment || 0;
    value += increment;
    if (increment > 0) {
    if (!value) {
    return value;

checkPath(...) API Documentation

Can be used to call a function once all of the desired asynchronous calls have been successfully made.


  1. callback {function(positiveCallCount)}:
    The callback which will be called as soon as the amount of positive and negative calls to the returned function even out.
  2. opt_initial {number}:
    Optional. Defaults to 0. Number to start off at.


A function which can be passed true which is the same as passing 1, false which is the same as passing -1, undefined or no arguments which come out to be -1 or a value which is coerced to a number. The number passed in will be added to the internal value (which starts off as opt_initial. If the internal value comes to be 0 the callback will be called with the one argument passed specifying how many times this returned function was positively called.


Imagine that we want to see how long it really takes setInterval() with a wait period of 0ms to run a function of basically nothing 1000 times:
var start = new Date,
    interval = setInterval(function() { f(); }, 0),
    f = YourJS.on0(function(count) {
      console.log('It took ' + (new Date - start) + 'ms to count to ' + count + '.');

for (var i = 0; i < 1000; i++) {
When I run the above code it takes roughly 3990ms despite the fact that we give setInterval() a wait of 0ms. This shows that setting too low of a wait time will have no effect.