前端JS如何創(chuàng)建一個(gè)可隨時(shí)取消的定時(shí)器
一、原生的取消方式
JavaScript 原生就提供了取消定時(shí)器的方法。setTimeout 和 setInterval 在調(diào)用時(shí)都會(huì)返回一個(gè)數(shù)字類(lèi)型的 ID,我們可以將這個(gè) ID 傳遞給 clearTimeout 或 clearInterval 來(lái)取消它。
// 1. 設(shè)置一個(gè)定時(shí)器
const timerId: number = setTimeout(() => {
console.log("這個(gè)消息可能永遠(yuǎn)不會(huì)被打印");
}, 2000);
// 2. 在它觸發(fā)前取消它
clearTimeout(timerId);
常見(jiàn)痛點(diǎn):
timerId變量需要被保留在組件或模塊的作用域中,狀態(tài)分散。- 啟動(dòng)、暫停、取消的邏輯是割裂的,代碼可讀性和可維護(hù)性差。
二、封裝一個(gè)可取消的定時(shí)器類(lèi)
我們可以簡(jiǎn)單的封裝一個(gè) CancellableTimer 類(lèi),將定時(shí)器的狀態(tài)和行為內(nèi)聚在一起。后續(xù)可以擴(kuò)展,把項(xiàng)目中的所有定時(shí)器進(jìn)行統(tǒng)一管理。
// 定義定時(shí)器ID類(lèi)型
type TimeoutId = ReturnType<typeof setTimeout>;
class CancellableTimer {
private timerId: TimeoutId | null = null;
constructor(private callback: () => void, private delay: number) {}
public start(): void {
// 防止重復(fù)啟動(dòng)
if (this.timerId !== null) {
this.cancel();
}
this.timerId = setTimeout(() => {
this.callback();
// 執(zhí)行完畢后重置 timerId
this.timerId = null;
}, this.delay);
}
public cancel(): void {
if (this.timerId !== null) {
clearTimeout(this.timerId);
this.timerId = null;
}
}
}
// 使用示例
console.log('定時(shí)器將在3秒后觸發(fā)...');
const myTimer = new CancellableTimer(() => {
console.log('定時(shí)器任務(wù)執(zhí)行!');
}, 3000);
myTimer.start();
// 模擬在1秒后取消
setTimeout(() => {
console.log('用戶取消了定時(shí)器。');
myTimer.cancel();
}, 1000);
三、實(shí)現(xiàn)可暫停和恢復(fù)的定時(shí)器
在很多場(chǎng)景下,我們需要的不僅僅是取消,還有暫停和恢復(fù)。
要實(shí)現(xiàn)這個(gè)功能,我們需要在暫停時(shí)記錄剩余時(shí)間。
type TimeoutId = ReturnType<typeof setTimeout>;
class AdvancedTimer {
private timerId: TimeoutId | null = null;
private startTime: number = 0;
private remainingTime: number;
private callback: () => void;
private delay: number;
constructor(callback: () => void, delay: number) {
this.remainingTime = delay;
this.callback = callback;
this.delay = delay;
}
public resume(): void {
if (this.timerId) {
return; // 已經(jīng)在運(yùn)行
}
this.startTime = Date.now();
this.timerId = setTimeout(() => {
this.callback();
// 任務(wù)完成,重置
this.remainingTime = this.delay;
this.timerId = null;
}, this.remainingTime);
}
public pause(): void {
if (!this.timerId) {
return;
}
clearTimeout(this.timerId);
this.timerId = null;
// 計(jì)算并更新剩余時(shí)間
const timePassed = Date.now() - this.startTime;
this.remainingTime -= timePassed;
}
public cancel(): void {
if (this.timerId) {
clearTimeout(this.timerId);
}
this.timerId = null;
this.remainingTime = this.delay; // 重置
}
}
// 使用示例
console.log('定時(shí)器啟動(dòng),5秒后執(zhí)行...');
const advancedTimer = new AdvancedTimer(() => console.log('Done!'), 5000);
advancedTimer.resume();
setTimeout(() => {
console.log('2秒后暫停定時(shí)器');
advancedTimer.pause();
}, 2000);
setTimeout(() => {
console.log('4秒后恢復(fù)定時(shí)器 , 應(yīng)該還剩3秒');
advancedTimer.resume();
}, 4000);
到此這篇關(guān)于前端JS如何創(chuàng)建一個(gè)可隨時(shí)取消的定時(shí)器的文章就介紹到這了,更多相關(guān)JS創(chuàng)建可隨時(shí)取消定時(shí)器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript中類(lèi)的定義方式詳解(四種方式)
這篇文章主要介紹了javascript中類(lèi)的定義方式,結(jié)合實(shí)例形式較為詳細(xì)的分析了JavaScript中類(lèi)的四種定義方式,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-12-12
js實(shí)現(xiàn)點(diǎn)擊注冊(cè)按鈕開(kāi)始讀秒倒計(jì)時(shí)的小例子
js實(shí)現(xiàn)點(diǎn)擊注冊(cè)按鈕開(kāi)始讀秒倒計(jì)時(shí)的小例子,需要的朋友可以參考一下2013-05-05
JavaScript實(shí)現(xiàn)煙花綻放動(dòng)畫(huà)效果
這篇文章主要介紹了JavaScript如何實(shí)現(xiàn)煙花綻放動(dòng)畫(huà)效果,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-08-08
js實(shí)現(xiàn)倒計(jì)時(shí)(距離結(jié)束還有)示例代碼
本文與大家分享個(gè)js實(shí)現(xiàn)倒計(jì)時(shí)的代碼,主要實(shí)現(xiàn)功能距離結(jié)束還有多少時(shí)間,感興趣的朋友可以參考下,希望對(duì)大家學(xué)習(xí)js有所幫助2013-07-07
javascript中parseInt()函數(shù)的定義和用法分析
這篇文章主要介紹了javascript中parseInt()函數(shù)的定義和用法,較為詳細(xì)的分析了parseInt()函數(shù)的定義及具體用法,以及參數(shù)使用時(shí)的注意事項(xiàng),需要的朋友可以參考下2014-12-12

