interval.js

  1. /**
  2. * Source: https://gist.github.com/manast/1185904
  3. */
  4. function interval(duration, fn) {
  5. this.baseline = undefined
  6.  
  7. this.run = function() {
  8. if(this.baseline === undefined) {
  9. this.baseline = new Date().getTime()
  10. }
  11. fn()
  12. var end = new Date().getTime()
  13. this.baseline += duration
  14.  
  15. var nextTick = duration - (end - this.baseline)
  16. if(nextTick < 0) {
  17. nextTick = 0;
  18. }
  19. (function(i) {
  20. i.timer = setTimeout(function() {
  21. i.run(end)
  22. }, nextTick)
  23. }(this))
  24. }
  25.  
  26. this.stop = function() {
  27. clearTimeout(this.timer)
  28. }
  29. }
  30.  
  31. /*** Usage ***/
  32.  
  33. var timer = new interval(50, function() {
  34. console.log(new Date().getTime())
  35. })
  36. timer.run()
  37.  
  38.