@georapbox/timer

Minimal javascript library to create and manage timers in the browser

Usage no npm install needed!

<script type="module">
  import georapboxTimer from 'https://cdn.skypack.dev/@georapbox/timer';
</script>

README

npm version Build Status Coverage Status dependencies Status devDependencies Status License: MIT

Timer

Minimal javascript library to create and manage timers

NOTE: Depends on window.requestAnimationFrame. If your environment does not support it, you can polyfill.

Install

$ npm install @georapbox/timer --save

Usage

The library is exported in UMD, CommonJS, and ESM formats. You can import it the following ways:

Using ESM import statement

import Timer from '@georapbox/timer';

Using CommonJS require statement

const Timer = require('@georapbox/timer').default;

As old school browser global

<script src="https://unpkg.com/@georapbox/timer"></script>

API

new Timer([duration], [callback])

Creates a Timer instance.

Param Type Description
[duration] Number The timer's duration (ms). If left undefined or 0 or negative number the timer counts up instead of down.
[callback] function Function to be executed while timer is running. The Timer instance is passed by as parameter.

timer.time() ⇒ Object

Get the remaining and elapsed time.
If no duration is specified during initialization, the remaining time will always be 0.

Kind: instance method of Timer
Returns: Object - An object that contains the remaining and the elapsed time in milliseconds.

timer.start([shouldReset]) ⇒ Timer

Start the timer.
If the timer instance has been already started, the timer will just resume.

Kind: instance method of Timer
Returns: Timer - The Timer instance.

Param Type Description
[shouldReset] Boolean If set to true, the timer will reset to initial specified duration.

timer.stop() ⇒ Timer

Stop/Pause the timer.

Kind: instance method of Timer
Returns: Timer - The Timer instance.

timer.reset([shouldStop]) ⇒ Timer

Resets the timer to initial specified duration.

Kind: instance method of Timer
Returns: Timer - The Timer instance.

Param Type Description
[shouldStop] Boolean If set to true, the timer will be forced to stop; otherwise will reset and continue running.

timer.isRunning() ⇒ Boolean

Check (at any time) if the timer is running or not.

Kind: instance method of Timer
Returns: Boolean - True if the timer is running; otherwise false.

Test

$ npm run test

License

The MIT License (MIT)