Advertisement
Guest User

Untitled

a guest
Jul 27th, 2017
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. let deferreds = {} as { [key : string] : any[] }
  2. let deferred_timers = {} as { [key : string] : number }
  3.  
  4. /*
  5. * If you're waiting wor a `window.something`, and are not sure when it
  6. * will appear (for example, you defer async load it), you can do the following:
  7. *
  8. * defer('something', (something) => ...)
  9. *
  10. * You can also check nested props:
  11. *
  12. * defer('google.maps', (GoogleMaps) => ...)
  13. *
  14. *
  15. * defer will poll window['something'], and when it appears, it will
  16. * invoke the function with window['something']
  17. *
  18. * Note: it will poll the window object for 90 seconds, and then will stop
  19. *
  20. */
  21.  
  22. export default function defer(what : string, action : Function) : void {
  23. const executeAndLog = (whatObj, actionFunc) => {
  24. if(what === 'mixpanel') {
  25. // console.log(what, actionFunc.toString())
  26. }
  27. actionFunc(whatObj)
  28. }
  29.  
  30. const obj = checkNested(window, what.split('.'))
  31.  
  32. if(obj !== void 0) {
  33. const actions = deferreds[what] || []
  34.  
  35. actions.forEach((action) => executeAndLog(obj, action))
  36. executeAndLog(obj, action)
  37. } else {
  38. if(deferreds[what] === void 0) {
  39. deferreds[what] = []
  40. }
  41.  
  42. deferreds[what].push(action)
  43. if(deferred_timers[what] === void 0) {
  44. let counter = 0
  45. deferred_timers[what] = setInterval(() => {
  46. const obj = checkNested(window, what.split('.'))
  47. if(obj !== void 0) {
  48. clearInterval(deferred_timers[what])
  49. const actions = deferreds[what] || []
  50. actions.forEach((action) => executeAndLog(obj, action))
  51. } else {
  52. counter = counter + 1
  53. if(counter > 300) {
  54. clearInterval(deferred_timers[what])
  55. }
  56. }
  57. }, 300)
  58. }
  59. }
  60. }
  61.  
  62. function checkNested(obj, what) {
  63. for(let i = 0; i < what.length; i++) {
  64. if(!obj || !obj.hasOwnProperty(what[i])) {
  65. return void 0
  66. }
  67. obj = obj[what[i]]
  68. }
  69. return obj
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement