前端JS如何創(chuàng)建一個可隨時取消的定時器
一、原生的取消方式
JavaScript 原生就提供了取消定時器的方法。setTimeout 和 setInterval 在調(diào)用時都會返回一個數(shù)字類型的 ID,我們可以將這個 ID 傳遞給 clearTimeout 或 clearInterval 來取消它。
// 1. 設(shè)置一個定時器
const timerId: number = setTimeout(() => {
console.log("這個消息可能永遠(yuǎn)不會被打印");
}, 2000);
// 2. 在它觸發(fā)前取消它
clearTimeout(timerId);
常見痛點:
timerId變量需要被保留在組件或模塊的作用域中,狀態(tài)分散。- 啟動、暫停、取消的邏輯是割裂的,代碼可讀性和可維護(hù)性差。
二、封裝一個可取消的定時器類
我們可以簡單的封裝一個 CancellableTimer 類,將定時器的狀態(tài)和行為內(nèi)聚在一起。后續(xù)可以擴(kuò)展,把項目中的所有定時器進(jìn)行統(tǒng)一管理。
// 定義定時器ID類型
type TimeoutId = ReturnType<typeof setTimeout>;
class CancellableTimer {
private timerId: TimeoutId | null = null;
constructor(private callback: () => void, private delay: number) {}
public start(): void {
// 防止重復(fù)啟動
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('定時器將在3秒后觸發(fā)...');
const myTimer = new CancellableTimer(() => {
console.log('定時器任務(wù)執(zhí)行!');
}, 3000);
myTimer.start();
// 模擬在1秒后取消
setTimeout(() => {
console.log('用戶取消了定時器。');
myTimer.cancel();
}, 1000);
三、實現(xiàn)可暫停和恢復(fù)的定時器
在很多場景下,我們需要的不僅僅是取消,還有暫停和恢復(fù)。
要實現(xiàn)這個功能,我們需要在暫停時記錄剩余時間。
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;
// 計算并更新剩余時間
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('定時器啟動,5秒后執(zhí)行...');
const advancedTimer = new AdvancedTimer(() => console.log('Done!'), 5000);
advancedTimer.resume();
setTimeout(() => {
console.log('2秒后暫停定時器');
advancedTimer.pause();
}, 2000);
setTimeout(() => {
console.log('4秒后恢復(fù)定時器 , 應(yīng)該還剩3秒');
advancedTimer.resume();
}, 4000);
到此這篇關(guān)于前端JS如何創(chuàng)建一個可隨時取消的定時器的文章就介紹到這了,更多相關(guān)JS創(chuàng)建可隨時取消定時器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用js驗證hash,content hash , chunk hash的區(qū)別解
crypto-js是一個JavaScript加密算法庫,用于實現(xiàn)各種加密算法和哈希函數(shù),它提供了一種簡單而強(qiáng)大的方式來執(zhí)行加密操作,包括對稱加密算法、非對稱加密算法和哈希函數(shù)等,本文給大家介紹使用js驗證hash,content hash , chunk hash的區(qū)別解析,感興趣的朋友跟隨小編一起看看吧2024-12-12
JS實現(xiàn)商城秒殺倒計時功能(動態(tài)設(shè)置秒殺時間)
這篇文章主要介紹了JS實現(xiàn)商城秒殺倒計時功能(動態(tài)設(shè)置秒殺時間),本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12
javascript實現(xiàn)table選中的行以指定顏色高亮顯示的方法
這篇文章主要介紹了javascript實現(xiàn)table選中的行以指定顏色高亮顯示的方法,實例分析了javascript操作table表格元素與相關(guān)樣式的技巧,需要的朋友可以參考下2015-05-05
Javascript 鍵盤事件的組合使用實現(xiàn)代碼
Javascript 鍵盤事件的組合使用實現(xiàn)代碼,需要的朋友可以參考下2012-05-05
(跨瀏覽器基礎(chǔ)事件/瀏覽器檢測/判斷瀏覽器)經(jīng)驗代碼分享
一些js代碼,自己備用的,高手不要笑話我。(跨瀏覽器基礎(chǔ)事件,瀏覽器檢測,判斷瀏覽器的名稱、版本號、操作系統(tǒng))等等,很實用的,方便自己使用,感興趣的朋友可以了解下,希望本文對你有所幫助2013-01-01

