求JavaScript中NSTimer的等效实现:支持延迟执行、取消与重置
Hey there! If you're coming from iOS development and need an NSTimer-like tool in JavaScript, we can build a flexible wrapper that hits all your requirements: delayed code execution, on-demand cancellation, and interval resets. Here's a robust, easy-to-use solution:
Custom Timer Class (NSTimer Equivalent)
This class mimics NSTimer's core behavior, using JavaScript's built-in setTimeout/setInterval under the hood while adding the control you need:
class Timer { constructor(callback, delay, isRepeating = false) { this.callback = callback; this.delay = delay; this.isRepeating = isRepeating; this.timerId = null; this._start(); } // Internal method to start the timer _start() { if (this.isRepeating) { this.timerId = setInterval(() => { this.callback(); }, this.delay); } else { this.timerId = setTimeout(() => { this.callback(); // Auto-cleanup for one-time timers this.timerId = null; }, this.delay); } } // *Equivalent to NSTimer's `invalidate()`*: Cancel the timer immediately invalidate() { if (this.timerId) { this.isRepeating ? clearInterval(this.timerId) : clearTimeout(this.timerId); this.timerId = null; } } // Reset the timer with a new delay (uses original delay if no new value is provided) reset(newDelay = this.delay) { // Cancel existing timer first this.invalidate(); // Update delay if a new one is passed this.delay = newDelay; // Restart the timer this._start(); } }
How to Use It
Let's walk through examples matching your use cases:
1. Execute Code After a Specified Interval
Create a one-time timer (just like NSTimer with repeats: NO):
// Fire a function after 2 seconds const oneTimeTimer = new Timer(() => { console.log("One-time timer triggered!"); }, 2000); // Cancel it anytime before it fires (uncomment to test) // oneTimeTimer.invalidate();
2. Cancel Execution On-Demand
Use the invalidate() method to stop a repeating or pending timer:
// Repeat a function every 1 second const repeatingTimer = new Timer(() => { console.log("Repeating timer tick!"); }, 1000, true); // Cancel the timer after 5 seconds setTimeout(() => { repeatingTimer.invalidate(); console.log("Repeating timer cancelled successfully"); }, 5000);
3. Reset the Timer's Interval
Update the delay and restart the timer with reset():
const timer = new Timer(() => { console.log("Timer fired!"); }, 3000); // After 1 second, reset the timer to fire after 5 seconds instead setTimeout(() => { timer.reset(5000); console.log("Timer reset to 5-second delay"); }, 1000);
Key Details
- Safe Cancellation: Calling
invalidate()on a timer that's already fired or cancelled does nothing—no errors to worry about, just like NSTimer. - Memory Management: The class clears timer references when cancelled or completed, avoiding unintended memory leaks.
- Flexibility: Works for both one-time and repeating timers, just like NSTimer.
内容的提问来源于stack exchange,提问作者Kishoretheju
相关产品推荐
相关产品推荐

