前端JS如何創(chuàng)建一個可隨時取消的定時器
一、原生的取消方式
JavaScript 原生就提供了取消定時器的方法。setTimeout 和 setInterval 在調用時都會返回一個數(shù)字類型的 ID,我們可以將這個 ID 傳遞給 clearTimeout 或 clearInterval 來取消它。
// 1. 設置一個定時器
const timerId: number = setTimeout(() => {
console.log("這個消息可能永遠不會被打印");
}, 2000);
// 2. 在它觸發(fā)前取消它
clearTimeout(timerId);
常見痛點:
timerId變量需要被保留在組件或模塊的作用域中,狀態(tài)分散。- 啟動、暫停、取消的邏輯是割裂的,代碼可讀性和可維護性差。
二、封裝一個可取消的定時器類
我們可以簡單的封裝一個 CancellableTimer 類,將定時器的狀態(tài)和行為內聚在一起。后續(xù)可以擴展,把項目中的所有定時器進行統(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 {
// 防止重復啟動
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('定時器任務執(zhí)行!');
}, 3000);
myTimer.start();
// 模擬在1秒后取消
setTimeout(() => {
console.log('用戶取消了定時器。');
myTimer.cancel();
}, 1000);
三、實現(xiàn)可暫停和恢復的定時器
在很多場景下,我們需要的不僅僅是取消,還有暫停和恢復。
要實現(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; // 已經在運行
}
this.startTime = Date.now();
this.timerId = setTimeout(() => {
this.callback();
// 任務完成,重置
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秒后恢復定時器 , 應該還剩3秒');
advancedTimer.resume();
}, 4000);
到此這篇關于前端JS如何創(chuàng)建一個可隨時取消的定時器的文章就介紹到這了,更多相關JS創(chuàng)建可隨時取消定時器內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
javascript中parseInt()函數(shù)的定義和用法分析
這篇文章主要介紹了javascript中parseInt()函數(shù)的定義和用法,較為詳細的分析了parseInt()函數(shù)的定義及具體用法,以及參數(shù)使用時的注意事項,需要的朋友可以參考下2014-12-12

