dbounce.js

Basic thread-wide de-bounce helper
git clone git://git.finwo.net/lib/dbounce.js
Log | Files | Refs | README

index.js (708B)


      1 const state = {};
      2 
      3 export function dbounce(name, ttl = 100) {
      4 
      5   // Close previous caller
      6   if (state[name]) {
      7     clearTimeout(state[name].timer);
      8     state[name].resolve(false);
      9   }
     10 
     11   // Externally-resolvable promise
     12   const ref = state[name] = {};
     13   ref.promise = new Promise(resolve => {
     14     ref.resolve = arg => {
     15       resolve(arg);
     16     };
     17   });
     18 
     19   // Add a timer to it
     20   ref.timer = setTimeout(() => {
     21     if (state[name] !== ref) return; // Something else closed this ref
     22     delete state[name];              // Close, prevent others from accessing this ref
     23     ref.resolve(true);               // Indicate this ref triggered
     24   }, ttl);
     25 
     26   // Return the promise as black-box
     27   return ref.promise;
     28 }