Created
          October 13, 2011 13:43 
        
      - 
      
 - 
        
Save vstarck/1284252 to your computer and use it in GitHub Desktop.  
    Infinite async loop
  
        
  
    
      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
    
  
  
    
  | var infiniteTimedLoop = (function() { | |
| var | |
| task, | |
| interval = 100, | |
| status = false, | |
| i = 0; | |
| function start() { | |
| if(!status) { | |
| return; | |
| } | |
| task(i++); | |
| setTimeout(start, interval); | |
| }; | |
| return { | |
| setInterval: function(ms) { | |
| interval = ms; | |
| return this; | |
| }, | |
| start: function() { | |
| status = true; | |
| start(); | |
| return this; | |
| }, | |
| stop: function() { | |
| status = false; | |
| return this; | |
| }, | |
| sleep: function(ms) { | |
| var self = this; | |
| this.stop(); | |
| setTimeout(self.start, ms); | |
| return this; | |
| }, | |
| do: function(newTask) { | |
| task = newTask; | |
| return this; | |
| } | |
| }; | |
| })(); | |
| // API | |
| // Set the task | |
| infiniteTimedLoop.do(console.log); | |
| // Start | |
| infiniteTimedLoop.start(); | |
| // Sleep 1 second (1000 ms) | |
| infiniteTimedLoop.sleep(1000); | |
| // Stop | |
| infiniteTimedLoop.stop(); | |
| // And start again! | |
| infiniteTimedLoop.start(); | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment