index.js 871 B

1234567891011121314151617181920212223242526272829303132333435
  1. var tick = 1
  2. var maxTick = 65535
  3. var resolution = 4
  4. var inc = function () {
  5. tick = (tick + 1) & maxTick
  6. }
  7. var timer = setInterval(inc, (1000 / resolution) | 0)
  8. if (timer.unref) timer.unref()
  9. module.exports = function (seconds) {
  10. var size = resolution * (seconds || 5)
  11. var buffer = [0]
  12. var pointer = 1
  13. var last = (tick - 1) & maxTick
  14. return function (delta) {
  15. var dist = (tick - last) & maxTick
  16. if (dist > size) dist = size
  17. last = tick
  18. while (dist--) {
  19. if (pointer === size) pointer = 0
  20. buffer[pointer] = buffer[pointer === 0 ? size - 1 : pointer - 1]
  21. pointer++
  22. }
  23. if (delta) buffer[pointer - 1] += delta
  24. var top = buffer[pointer - 1]
  25. var btm = buffer.length < size ? 0 : buffer[pointer === size ? 0 : pointer]
  26. return buffer.length < resolution ? top : (top - btm) * resolution / buffer.length
  27. }
  28. }