testing clearAllTimeouts

by Neil Kalman

HTML

<link rel="stylesheet" href="https://thatkookooguy.github.io/jsfiddle-console/console.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://thatkookooguy.github.io/jsfiddle-console/console.js"></script>

JavaScript

(function(window) {
  const oldTimeout = window.setTimeout;
  let timeoutIds = [];

  window.setTimeout = (callback, timeout) => {
    console.debug('NEW setTimeout was called');
    if (!callback) return;

    timeout = timeout || 0;

    const id = oldTimeout(function() {
      callback();

      const index = timeoutIds.indexOf(id);
      if (index > -1) {
        timeoutIds.splice(index, 1);
      }
    }, timeout);

    if (id) {
      timeoutIds.push(id)
    }

    return id;
  };

  window.clearAllTimeouts = () => {
    console.debug('clearAllTimeouts was called');
    // PART B
    const currentValue = window.localStorage.getItem('clearAll');
    window.localStorage.setItem('clearAll', currentValue !== 'true');
    // END PART B
    clearTimeoutsHelper();
  };

  // PART B
  window.addEventListener('storage', (event) => {
    console.debug('storage event fired');
    // don't remember the exact API
    if (event.key === 'clearAll') {

      clearTimeoutsHelper();
    }
  });
  // END PART B

  function clearTimeoutsHelper() {
    timeoutIds.forEach((id) => {
      window.clearTimeout(id);
    });

    timeoutIds = [];
  }
})(window);


setTimeout(() => console.error('very nice!'), 3000);


clearAllTimeouts();