Skip to content

dimensionalpocket/timer-js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

26 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@dimensionalpocket/timer

build Total alerts Language grade: JavaScript

Opinionated wrapper for Javascript's setInterval and setTimeout functions.

Usage

import Timer from '@dimensionalpocket/timer'

// Timer instance is provided in event.
// A `counter` property is incremented on tick.
var myFunc = (timer) => console.log('Hello world! Times:', this.counter)

// Initialize a timer but don't start it yet.
// Available events: tick, start, stop
var timer = new Timer({duration: 1000})
timer.on('tick', myFunc)

// Will fire callback once after 1s.
// Can be called multiple times.
// Each time start() is called, it will cancel any running timers.
timer.start()

// Cancel any active timeouts/intervals, preserving callback and settings.
timer.stop()

// Starts after 5s (so callback will be fired after 6s).
timer.start({delay: 5000})

// Fires callback 5 times every 1 second then stops.
timer.start({repeat: 5})

// Fires callback 5 times every 1 second, with a 5s delay before the first call.
timer.start({delay: 5000, repeat: 5})

// Loops infinitely until stop() is called.
timer.start({repeat: -1})
// Or
timer.start({loop: true})

// Infinite loops can be combined with delayed starts.
// The first call will fire at 6s, then loop infinitely every 1s.
timer.start({delay: 5000, loop: true})

// If you prefer to use `setInterval` internally for looping:
timer.start({loop: true, interval: true})
timer.start({repeat: 5, interval: true})

License

MIT