test.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. 'use strict'
  2. const test = require('tape')
  3. const retimer = require('./')
  4. test('schedule a callback', function (t) {
  5. t.plan(1)
  6. const start = Date.now()
  7. retimer(function () {
  8. t.ok(Date.now() - start >= 50, 'it was deferred ok!')
  9. }, 50)
  10. })
  11. test('reschedule a callback', function (t) {
  12. t.plan(1)
  13. const start = Date.now()
  14. const timer = retimer(function () {
  15. t.ok(Date.now() - start >= 70, 'it was deferred ok!')
  16. }, 50)
  17. setTimeout(function () {
  18. timer.reschedule(50)
  19. }, 20)
  20. })
  21. test('reschedule multiple times', function (t) {
  22. t.plan(1)
  23. const start = Date.now()
  24. const timer = retimer(function () {
  25. t.ok(Date.now() - start >= 90, 'it was deferred ok!')
  26. }, 50)
  27. setTimeout(function () {
  28. timer.reschedule(50)
  29. setTimeout(function () {
  30. timer.reschedule(50)
  31. }, 20)
  32. }, 20)
  33. })
  34. test('clear a timer', function (t) {
  35. t.plan(1)
  36. const timer = retimer(function () {
  37. t.fail('the timer should never get called')
  38. }, 20)
  39. timer.clear()
  40. setTimeout(function () {
  41. t.pass('nothing happened')
  42. }, 50)
  43. })
  44. test('clear a timer after a reschedule', function (t) {
  45. t.plan(1)
  46. const timer = retimer(function () {
  47. t.fail('the timer should never get called')
  48. }, 20)
  49. setTimeout(function () {
  50. timer.reschedule(50)
  51. setTimeout(function () {
  52. timer.clear()
  53. }, 10)
  54. }, 10)
  55. setTimeout(function () {
  56. t.pass('nothing happened')
  57. }, 50)
  58. })
  59. test('can be rescheduled early', function (t) {
  60. t.plan(1)
  61. const start = Date.now()
  62. const timer = retimer(function () {
  63. t.ok(Date.now() - start <= 500, 'it was rescheduled!')
  64. }, 500)
  65. setTimeout(function () {
  66. timer.reschedule(10)
  67. }, 20)
  68. })
  69. test('can be rescheduled even if the timeout has already triggered', function (t) {
  70. t.plan(2)
  71. const start = Date.now()
  72. let count = 0
  73. const timer = retimer(function () {
  74. count++
  75. if (count === 1) {
  76. t.ok(Date.now() - start >= 20, 'it was triggered!')
  77. timer.reschedule(20)
  78. } else {
  79. t.ok(Date.now() - start >= 40, 'it was rescheduled!')
  80. }
  81. }, 20)
  82. })
  83. test('pass arguments to the callback', function (t) {
  84. t.plan(1)
  85. retimer(function (arg) {
  86. t.equal(arg, 42, 'argument matches')
  87. }, 50, 42)
  88. })