trial-meter.js 664 B

1234567891011121314151617181920212223242526272829303132333435
  1. /**
  2. * 试看时长计量(秒);-1 表示免费全场
  3. */
  4. export class TrialMeter {
  5. constructor(onExpire) {
  6. this.onExpire = onExpire
  7. this.secondsLeft = null
  8. this._timer = null
  9. }
  10. start(seconds) {
  11. this.stop()
  12. this.secondsLeft = seconds
  13. if (seconds === -1 || seconds === null || seconds === undefined) return
  14. if (seconds <= 0) {
  15. this.onExpire?.()
  16. return
  17. }
  18. this._timer = setInterval(() => {
  19. if (this.secondsLeft <= 0) return
  20. this.secondsLeft -= 1
  21. if (this.secondsLeft <= 0) {
  22. this.stop()
  23. this.onExpire?.()
  24. }
  25. }, 1000)
  26. }
  27. stop() {
  28. if (this._timer) {
  29. clearInterval(this._timer)
  30. this._timer = null
  31. }
  32. }
  33. }