npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@osiris-smarttv/worker-timer

v0.1.0

Published

Global Worker Timer system for React applications - efficient single timer serving multiple components

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-timer
yarn add @osiris-smarttv/worker-timer

Quick 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(): void

Instance 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[]): boolean

Events

import { WorkerEvent } from '@osiris-smarttv/worker-timer'

WorkerEvent.TimeApp // 'TimeApp' - Emitted on each timer tick
WorkerEvent.Status // 'Status' - Emitted on status changes

Utility 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 issues

Global 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, efficient

Performance 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 install

Scripts

# 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 checking

Project 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 test

Tests 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

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📝 License

MIT License - see the LICENSE file for details.

🔗 Links

💡 Support

For support and questions, please open an issue on GitHub Issues.


Made with ❤️ by Osiris Smart TV Team