当用户需要发短信时就用到了倒计时的功能,这时就要用到循环定时器setInterval(),但是当用户切换到后台运行时定时器就停止了运行,于是考虑使用系统时间来实现这个功能。
var count = ''; var timer = null; showTime() { var oldTime = new Date().getTime() / 1000; const TIME_COUNT = 60; if (!this.timer) { this.count = TIME_COUNT; this.timer = setInterval(() => { var newTime = new Date().getTime() / 1000; var time = Math.round(newTime - oldTime); if (this.count > 0 && this.count <= TIME_COUNT) { this.count = 60 - time; } else { clearInterval(this.timer); this.timer = null; } }, 1000); } },
destroyed() { clearInterval(this.timer); }
注意:当用户离开当前页面时需要将定时器清除,否则用户在倒计时的时间内再次进来会看到倒计时依然在运行,用户体验大大下降。