ntc.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. class NumberTimeChange {
  2. constructor(options) {
  3. var data = {
  4. start: 0,
  5. end: 0,
  6. duration: 500,
  7. speed: 50,
  8. update: function (res) { },
  9. complete: function (res) { }
  10. }
  11. this.options = Object.assign(data, options)
  12. this.loops = Math.ceil(this.options.duration / this.options.speed);
  13. this.unit = Math.ceil(this.options.end - this.options.start)
  14. this.unit = this.unit < 0 ? this.unit - 9 : this.unit
  15. this.unit = Math.ceil(this.unit / this.loops)
  16. this.interval = null
  17. this.init()
  18. }
  19. init() {
  20. if (this.options.start == this.options.end){
  21. this.options.complete(this.options.start)
  22. return
  23. }
  24. if (this.unit == 0){
  25. this.options.start = this.options.end
  26. this.options.complete(this.options.start)
  27. return
  28. }
  29. this.interval = setInterval(function () {
  30. this.main()
  31. }.bind(this), this.options.speed)
  32. }
  33. main() {
  34. var isEnd = this.unit >= 0 ? this.options.start >= this.options.end : this.options.start <= this.options.end
  35. this.options.start += this.unit
  36. if (isEnd) {
  37. clearInterval(this.interval)
  38. this.options.start = this.options.end
  39. this.options.complete(this.options.start)
  40. } else {
  41. this.options.update(this.options.start)
  42. }
  43. }
  44. }
  45. export default NumberTimeChange