@osiris-smarttv/worker-timer
v0.1.0
Published
Global Worker Timer system for React applications - efficient single timer serving multiple components
Maintainers
Readme
@osiris-smarttv/worker-timer
A high-performance Global Worker Timer system for React applications. Provides a single, efficient Web Worker-based timer that can serve multiple components simultaneously, eliminating the need for multiple timer instances and reducing memory overhead.
GitHub Repository: OsirisTech-SmartTV/worker-timer
🚀 Features
- 🎯 Single Global Timer: One Web Worker timer serves the entire application
- ⚡ High Performance: Non-blocking execution in Web Worker thread
- 💾 Memory Efficient: Eliminates multiple timer instances
- 🔄 Dynamic Interval: Change timer interval at runtime for all listeners
- ⚛️ React Hooks: Easy-to-use React hooks integration
- 📡 Event-Driven: EventEmitter pattern for multiple listeners
- 🎮 Smart TV Ready: Optimized for Smart TV platforms
- 💪 TypeScript: Full TypeScript support with type definitions
- 📦 Multiple Formats: ESM and CommonJS support
Installation
npm install @osiris-smarttv/worker-timeryarn add @osiris-smarttv/worker-timerQuick Start
Basic Usage with React Hooks
import React from 'react'
import { useWorkerTimer, useCountDown } from '@osiris-smarttv/worker-timer'
function TimerComponent() {
// Global timer hook
const { isRunning, lastTick, start, stop, setInterval } = useWorkerTimer({
onTimerApp: (timestamp) => {
console.log('Timer tick:', new Date(timestamp).toLocaleTimeString())
},
interval: 1000,
autoStart: true
})
return (
<div>
<h2>Global Timer Status: {isRunning ? '🟢 Running' : '🔴 Stopped'}</h2>
<p>Last Tick: {new Date(lastTick).toLocaleTimeString()}</p>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
<button onClick={() => setInterval(500)}>Set 0.5s Interval</button>
<button onClick={() => setInterval(2000)}>Set 2s Interval</button>
</div>
)
}
function CountdownComponent() {
const { timeRemaining, isRunning, reset, pause, resume } = useCountDown({
initialTime: 60,
intervalType: 'worker', // Use global worker timer
onTimeUp: () => alert('🎉 Countdown finished!'),
autoStart: true
})
return (
<div>
<h2>Countdown: {timeRemaining}s</h2>
<p>Status: {isRunning ? 'Running' : 'Paused'}</p>
<button onClick={() => reset(60)}>Reset 60s</button>
<button onClick={() => reset(30)}>Reset 30s</button>
<button onClick={pause}>Pause</button>
<button onClick={resume}>Resume</button>
</div>
)
}
function App() {
return (
<div>
<h1>Global Worker Timer Demo</h1>
<TimerComponent />
<CountdownComponent />
{/* Both components use the same global timer! */}
</div>
)
}Direct Usage with AppWorkerManager
import { AppWorkerManager } from '@osiris-smarttv/worker-timer'
// Get global timer instance
const timer = AppWorkerManager.getInstance()
// Start timer with 1 second interval
timer.setInterval(1000)
timer.start()
// Listen to tick events
const unsubscribeTick = timer.onTick((timestamp) => {
console.log('Tick:', new Date(timestamp).toLocaleTimeString())
})
// Listen to status changes
const unsubscribeStatus = timer.onStatusChange((status) => {
console.log('Status:', status)
})
// Control timer
timer.stop()
timer.setInterval(500) // Change to 0.5 seconds
timer.start()
// Cleanup
unsubscribeTick()
unsubscribeStatus()📚 API Reference
Hooks
useWorkerTimer(options?)
Hook for accessing the global worker timer with automatic cleanup.
const {
isRunning, // boolean: Timer running state
lastTick, // number: Last tick timestamp
start, // () => void: Start timer
stop, // () => void: Stop timer
setInterval, // (ms: number) => void: Change interval
getStatus, // () => void: Request status
getGlobalTimer // () => AppWorkerManager: Get timer instance
} = useWorkerTimer({
onTimerApp?: (timestamp: number) => void, // Tick callback
onStatusChange?: (status: any) => void, // Status callback
interval?: number, // Timer interval (default: 1000ms)
autoStart?: boolean // Auto-start timer (default: true)
})useCountDown(options?)
Hook for countdown functionality using the global timer.
const {
timeRemaining, // number: Current countdown value
isRunning, // boolean: Countdown running state
reset, // (newTime?: number) => void: Reset countdown
pause, // () => void: Pause countdown
resume, // () => void: Resume countdown
setTimeRemaining // (time: number) => void: Set current time
} = useCountDown({
initialTime?: number, // Initial countdown value (default: 0)
onTimeUp?: () => void, // Called when countdown reaches minValue
intervalType?: 'worker' | 'interval', // Timer type (default: 'worker')
autoStart?: boolean, // Auto-start countdown (default: true)
interval?: number, // Timer interval (default: 1000ms)
minValue?: number // Minimum countdown value (default: 0)
})AppWorkerManager
Static Methods
// Get singleton instance
AppWorkerManager.getInstance(): AppWorkerManager
// Initialize global timer with interval
AppWorkerManager.initGlobalTimer(interval?: number): AppWorkerManager
// Get global timer (creates if not exists)
AppWorkerManager.getGlobalTimer(): AppWorkerManager
// Clear singleton instance
AppWorkerManager.clear(): voidInstance Methods
// Timer control
start(): void // Start timer
stop(): void // Stop timer
pause(): void // Pause timer (alias for stop)
resume(): void // Resume timer (alias for start)
setInterval(interval: number): void // Set timer interval
getStatus(): void // Request current status
// Event listeners
onTick(callback: (timestamp: number) => void): () => void
onStatusChange(callback: (status: any) => void): () => void
// EventEmitter methods
on(event: string, listener: Function): this
off(event: string, listener: Function): this
emit(event: string, ...args: any[]): booleanEvents
import { WorkerEvent } from '@osiris-smarttv/worker-timer'
WorkerEvent.TimeApp // 'TimeApp' - Emitted on each timer tick
WorkerEvent.Status // 'Status' - Emitted on status changesUtility Functions
import { createTimerWorker } from '@osiris-smarttv/worker-timer'
// Create new worker instance
const worker = createTimerWorker()
// Worker commands
worker.postMessage({ cmd: 'init', data?: { interval?: number } })
worker.postMessage({ cmd: 'start', data?: { interval?: number } })
worker.postMessage({ cmd: 'stop' })
worker.postMessage({ cmd: 'setInterval', data: number })
worker.postMessage({ cmd: 'getStatus' })🎯 Benefits of Global Timer System
Traditional Approach (Problems)
// ❌ Multiple timer instances
const Timer1 = () => {
useEffect(() => {
const interval = setInterval(callback1, 1000) // Timer 1
return () => clearInterval(interval)
}, [])
}
const Timer2 = () => {
useEffect(() => {
const interval = setInterval(callback2, 1000) // Timer 2
return () => clearInterval(interval)
}, [])
}
// Result: Multiple timers, more memory, potential sync issuesGlobal Timer Approach (Solution)
// ✅ Single global timer
const Timer1 = () => {
useWorkerTimer({ onTimerApp: callback1 }) // Listener 1
}
const Timer2 = () => {
useWorkerTimer({ onTimerApp: callback2 }) // Listener 2
}
// Result: One timer, multiple listeners, synchronized, efficientPerformance Comparison
| Aspect | Traditional Timers | Global Worker Timer | |--------|-------------------|---------------------| | Memory Usage | High (N timers) | Low (1 timer) | | CPU Usage | High (N intervals) | Low (1 interval) | | Synchronization | Not guaranteed | Perfect sync | | UI Blocking | Potential | Never (Web Worker) | | Management | Complex | Simple |
📱 Smart TV Optimization
This library is specifically optimized for Smart TV platforms:
- Memory Efficiency: Critical for resource-constrained TV environments
- Performance: Web Worker prevents UI blocking during intensive operations
- Reliability: Single timer source reduces complexity and potential failures
- Synchronization: All UI elements update in perfect sync
🏗️ Architecture
┌─────────────────────────────────────────────────────────────┐
│ React Application │
├─────────────────────────────────────────────────────────────┤
│ Component A │ Component B │ Component C │
│ useWorkerTimer │ useCountDown │ useWorkerTimer │
└─────────┬───────┴─────────┬───────┴─────────┬───────────────┘
│ │ │
└─────────────────┼─────────────────┘
│
┌─────────────────▼─────────────────┐
│ AppWorkerManager │
│ (EventEmitter) │
└─────────────────┬─────────────────┘
│
┌─────────────────▼─────────────────┐
│ Web Worker │
│ (createTimerWorker) │
│ │
│ setInterval(() => { │
│ postMessage(timestamp) │
│ }, interval) │
└──────────────────────────────────┘🛠️ Development
Prerequisites
- Node.js >= 14.0.0
- npm >= 6.0.0
Setup
git clone https://github.com/OsirisTech-SmartTV/worker-timer.git
cd worker-timer
npm installScripts
# Development
npm run dev # Start development server
npm run build # Build library
# Testing
npm run test # Run tests
npm run test:watch # Run tests in watch mode
npm run test:coverage # Run tests with coverage
# Code Quality
npm run lint # Check code style
npm run lint:fix # Fix code style issues
npm run format # Format code
npm run type-check # TypeScript type checkingProject Structure
src/
├── hooks/ # React hooks
│ ├── useCountdown.ts # Countdown hook using global timer
│ └── useWorkerTimer.ts # Global timer hook
├── manager/ # Timer manager
│ └── index.ts # AppWorkerManager (singleton)
├── utils/ # Utilities
│ └── timerWorker.ts # Web Worker creation
├── __tests__/ # Unit tests
│ ├── AppWorkerManager.test.ts
│ ├── useCountdown.test.ts
│ ├── useWorkerTimer.test.ts
│ └── timerWorker.test.ts
└── index.ts # Main exports🧪 Testing
npm testTests cover:
- ✅ Web Worker creation and commands
- ✅ AppWorkerManager singleton pattern
- ✅ React hooks functionality
- ✅ Event emitter patterns
- ✅ Memory management and cleanup
📄 Examples
Check out the examples directory for more detailed usage examples:
- Basic Timer: Simple timer implementation
- Multiple Countdowns: Multiple countdown components sharing one timer
- Performance Demo: Comparison with traditional timers
- Smart TV Integration: TV-specific optimizations
🤝 Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📝 License
MIT License - see the LICENSE file for details.
🔗 Links
- GitHub: https://github.com/OsirisTech-SmartTV/worker-timer
- NPM: https://www.npmjs.com/package/@osiris-smarttv/worker-timer
- Issues: https://github.com/OsirisTech-SmartTV/worker-timer/issues
💡 Support
For support and questions, please open an issue on GitHub Issues.
Made with ❤️ by Osiris Smart TV Team
