UNPKG

timer-basic

Version:

Simple timer package that enables recording time intervals between multiple events

71 lines (59 loc) 2.22 kB
// @ts-check /*! Timer.JS - v1.1.4 - 2019-04-2 * https://bitbucket.org/sachin1729/timer/ * * Copyright (c) 2019 Sachin Purohit; * Licensed under the ISC license */ var timer = (function(){ var handlesJSON = {}; var counter = 0 var handleBaseString = "handle" function start(handle){ counter = (counter+1)%1000000 if(!counter) console.warn("TIMER WARNING: Trying to create too many handles") if(!handle) handle = handleBaseString+counter handlesJSON[handle] = {} handlesJSON[handle].startTime = Date.now() handlesJSON[handle].intervals = [Date.now()] handlesJSON[handle].isRunning = true return handle } function pause(handle){ if(!handle) throw "Handle is required" if(!handlesJSON[handle]) throw "Invalid handle" if(!handlesJSON[handle].isRunning) throw "Timer is not running for this handle. Call resume() before pause()/stop()" var intervals = handlesJSON[handle].intervals var previousValue = intervals[intervals.length-1] handlesJSON[handle].intervals[intervals.length-1] = Date.now() - previousValue handlesJSON[handle].isRunning = false if(intervals.length == 1) return intervals[0] return intervals } function resume(handle){ if(!handle) throw "Handle is required" if(!handlesJSON[handle]) throw "Invalid handle" if(handlesJSON[handle].isRunning) throw "Call pause() before resume()" var newInterval = Date.now() handlesJSON[handle].intervals.push(newInterval) handlesJSON[handle].isRunning = true } // Stops the timer for this handle, deletes the handle and returns the array of intervals. function stop(handle){ var intervals = pause(handle) delete handlesJSON[handle] return intervals } function isRunning(handle){ if(!handle) throw "Handle is required" if(!handlesJSON[handle]) return false return handlesJSON[handle].isRunning } return { start, pause, resume, stop, isRunning } })(); if(typeof module != 'undefined' && module.exports) module.exports = timer