Last active
          June 1, 2016 17:42 
        
      - 
      
- 
        Save dsherret/824a94bdd6b68c995eeca8b7d5c70e1e to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | export class ThrottledQueue { | |
| private isThrottling = false; | |
| private items: (() => void)[] = []; | |
| constructor(private duration: number) { | |
| } | |
| run(item: () => void) { | |
| this.items.push(item); | |
| this.attemptExecute(); | |
| } | |
| private attemptExecute() { | |
| if (!this.isThrottling && this.items.length > 0) { | |
| this.execute(); | |
| } | |
| } | |
| private execute() { | |
| this.triggerThrottling(); | |
| this.runFirstItem(); | |
| } | |
| private triggerThrottling() { | |
| this.isThrottling = true; | |
| setTimeout(() => { | |
| this.isThrottling = false; | |
| this.attemptExecute(); | |
| }, this.duration); | |
| } | |
| private runFirstItem() { | |
| this.items[0](); | |
| this.items.shift(); | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Example use:
Which will output the date
50times every100ms