Guest User

Untitled

a guest
Sep 24th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. // isolated layer wrapper (for the local variables)
  2. (function(_W){
  3.  
  4. var cache = [], // will store all timeouts IDs
  5. _set = _W.setTimeout, // save original reference
  6. _clear = _W.clearTimeout; // save original reference
  7.  
  8. // Wrap original setTimeout with a function
  9. _W.setTimeout = function( CB, duration ){
  10. // also, wrap the callback, so the cache referece will be removed
  11. // when the timerout has reached (fired the callback)
  12. var id = _set(function(){
  13. CB();
  14. removeCacheItem(id);
  15. }, duration || 0);
  16.  
  17. cache.push( id ); // store reference in the cache array
  18.  
  19. // id must be returned to the user could save it and clear it if they choose to
  20. return id ;
  21. }
  22.  
  23. // Wrap original clearTimeout with a function
  24. _W.clearTimeout = function( id ){
  25. _clear(id);
  26. removeCacheItem(id);
  27. }
  28.  
  29. // Add a custom function named "clearTimeouts" to the "window" object
  30. _W.clearTimeouts = function(){
  31. cache.forEach(n => _clear(n))
  32. cache.length = [];
  33. }
  34.  
  35. // removes a specific id from the cache array
  36. function removeCacheItem( id ){
  37. var idx = cache.indexOf(id);
  38.  
  39. if( idx > -1 )
  40. cache = cache.filter(n => n != id )
  41. }
  42.  
  43. })(window);
Add Comment
Please, Sign In to add comment