Coder Social home page Coder Social logo

albert-gonzalez / easytimer.js Goto Github PK

View Code? Open in Web Editor NEW
753.0 18.0 232.0 1.99 MB

Easy to use Timer/Stopwatch/Countdown library compatible with AMD, ES6 and Typescript

Home Page: https://albert-gonzalez.github.io/easytimer.js/

License: MIT License

JavaScript 72.69% HTML 27.31%
amd nodejs javascript timer countdown chronometer vanilla-js es6 typescript stopwatch

easytimer.js's Introduction

easytimer.js

NPM

Easy to use Timer/Chronometer/Countdown library compatible with AMD and NodeJS

Install

NPM

npm install easytimer.js --save

Bower

bower install easytimer.js

Library Load

Script

<script src="lib/easytimer/dist/easytimer.min.js"></script>
<script>
  var timerInstance = new easytimer.Timer();
</script>

Node

var Timer = require("easytimer.js").Timer;
var timerInstance = new Timer();

// or

var { Timer } = require("easytimer.js");
var timerInstance = new Timer();

ES6 / Typescript Imports

import Timer from "easytimer.js";
const timer = new Timer();

// or

import { Timer } from "easytimer.js";
const timer = new Timer();

AMD

require(["node_modules/easytimer.js/dist/easytimer.min.js"], function (
  easytimer
) {
  var timer = new easytimer.Timer();
});

// or

require(["node_modules/easytimer.js/dist/easytimer.min.js"], function ({
  Timer,
}) {
  var timer = new Timer();
});

Examples

http://albert-gonzalez.github.io/easytimer.js/

Basic Usage

var timer = new Timer(/* default config */);
timer.start(/* config */);
timer.addEventListener("secondsUpdated", function (e) {
  $("#basicUsage").html(timer.getTimeValues().toString());
});

React

If you want to use EasyTimer with React, you can use the EasyTimer React Hook. You can check out the hook documentation here:

EasyTimer React Hook

Timer instance API

  • start(config): Start the timer
    • Parameters:
      • config (object):
        • startValues (object or array): The initial values of the timer when it is started
          • Accepted Values: Object with some of these keys: 'secondTenths', 'seconds', 'minutes', 'hours', 'days'. Or an array with this 5 positions: [secondTenths, seconds, minutes, hours, days]
          • Default Value (object or array): [0,0,0,0,0]
        • target (object or array): The target values that will make the timer to stop.
          • Accepted Values: Object with some of these keys: 'secondTenths', 'seconds', 'minutes', 'hours', 'days'. Or an array with this 5 positions: [secondTenths, seconds, minutes, hours, days]
          • Default Value: Undefined
        • precision (string): The timer update frequency.
          • Accepted Values: 'secondTenths', 'seconds', 'minutes', 'hours'
          • Default value: 'seconds'
        • callback (function): A callback function executed every time the timer is updated. The callback receives the timer as a parameter.
        • countdown (bool): If true, the timer is a countdown.
    • You can pass this same config when a Timer instance is created. For example: new Timer({ target: { seconds: 10 } }). This default config will be merged with the config passed to the start function.
  • stop(): Stop the timer
  • pause(): Pause the timer. After pause, you can call the start method without parameters to resume the timer.
  • reset(): Reset the timer values
  • isRunning(): Returns true if the timer is currently running.
  • isPaused(): Returns true if the timer is paused.
  • addEventListener(eventType, callback): Add a listener to an event. Timer triggers events when is updated
    • Events triggered:
      • secondTenthsUpdated
      • secondsUpdated
      • minutesUpdated
      • hoursUpdated
      • daysUpdated
      • targetAchieved
      • stopped
      • reset
      • started
      • paused
    • Parameters:
      • eventType (string): The type of the event that you want to listen.
      • callback (function): Function that will be executed when the timer triggers the specified event. The callback receives an object with the timer as a parameter.
  • on(eventType, callback): addEventListener alias.
  • removeEventListener(eventType, callback): Removes an event listener from the timer. Same usage as addEventListener.
  • off(eventType, callback): removeEventListener alias.
  • removeAllEventListeners(eventType): Removes all events listeners for the given type. If no type is given it will remove all event listeners.
  • getTimeValues(): Returns an object with the current values. The keys of the returned object are 'secondTenths', 'seconds', 'minutes', 'hours' and 'days'.
  • getTotalTimeValues(): Returns an object with the current absolute values. The keys of the returned object are 'secondTenths', 'seconds', 'minutes', 'hours' and 'days'.
  • getConfig(): Returns the configuration parameters.

Browser Support

Easytimer uses dispatchEvent, and this feature is available in these Browsers:

  • Chrome (version >= 4)
  • Firefox (version >= 2)
  • IE (version >= 9)
  • Opera (version >= 9)
  • Safari (version >= 3)
  • Mobile browsers

Known Issues

This library uses the Date class to calculate timer values. Date uses the system clock. If this clock is changed to a different date while the timer is running the timer values will be incorrect after that. If you know a way to fix that without losing time precision, please collaborate!

easytimer.js's People

Contributors

albert-gonzalez avatar alexdlm avatar avadh88 avatar hayrich avatar herberttn avatar jrebella avatar oneminch avatar ozdemirburak avatar pavlodeshko avatar zakuni avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

easytimer.js's Issues

tenthSeconds doesn't work on countdown

When i start the timer the secondTenths stays at :9 and never changes. Any idea what's going on here?
<script> var timer = new Timer(); $('#countdownExample .startButton').click(function () { timer.start({countdown: true, precision: 'secondTenths', startValues: {minutes: 3}}); }); $('#countdownExample .pauseButton').click(function () { timer.pause(); }); $('#countdownExample .resetButton').click(function () { timer.reset(); timer.pause(); }); timer.addEventListener('secondsUpdated', function (e) { $('#countdownExample .values').html(timer.getTimeValues().toString(['minutes', 'seconds', 'secondTenths'])); }); timer.addEventListener('started', function (e) { $('#countdownExample .values').html(timer.getTimeValues().toString(['minutes', 'seconds', 'secondTenths'])); }); timer.addEventListener('reset', function (e) { $('#countdownExample .values').html(timer.getTimeValues().toString(['minutes', 'seconds', 'secondTenths'])); }); </script>

Bug in "Interval of Tenth of Seconds"-Example

The code below worked for me. The bold words were wrong in the original code on the website.
The "secondTenthsUpdated" was "secondsUpdated" and the "getTimeVaules()" was "callbackTimer()".

var timer = new Timer();
timer.start({precision: 'secondTenths'});
timer.addEventListener('secondTenthsUpdated', function (e) {
$('#secondTenthsExample .values').html(timer.getTimeValues().toString(['hours', 'minutes', 'seconds', 'secondTenths']));
});

set starting timer?

It's possible to set a starter time?

instead of start the counter at 00:00:00, timer.setInitTime(00,12,32)
And the result will be timer.start() 00:12:32?

Countdown timer doesn't show days

Hi there, maximum allowed number of seconds is equivalent to 3600 x 24. Otherwise it only shows remaining hours.

for e.g. if 48 x 3600 is passed, it would count down from 24:00:00 rather 01:24:00:00

Also small feature request. There could be setting that would allow to hide unused zeroes. For e.g.:

instead: 00:01:59, it could show 01:59 if setting hide_zeroes:true

Change time method?

I'm interested in using this as a synchronization tool by synching videos/music up with the timer through sockets.

Does this have a method of changing time? Say you're at 55 seconds and you want to change time to 22 seconds?

Reset Countdown

Hello and thanks for this useful .js. I was wondering, is there a way I can reset a countdown even before it reaches 0? Thanks.

More than 24h

Is it possible to work longer than 24 hours?
Example: I worked a full year on the specific task, so I have 8766h
It's possible?

Hugs!

Cannot get rid of timer!

I have a table that has rows added and removed on a frequent basis. One of the cells in the table contains a span which is updated by a timer.

When I create the timer, I store the timer instance in an array, using the same id as the span.

When I get ready to remove the row, I get the id from the span, and then get the timer from the array.
I call stop(), I remove the event listener, and I then set that item in the array to null. However, the events for that timer are STILL firing.

I think the biggest issue is that the removeEventLister method doesn't seem to be working.

Question: Is there a way to preset the time before start?

Hi,

I'd like to preset the time before start, in my case seconds... for example:

I want to show: 00:00:10 before start (I need to count and no to countdown).

Is there a default way to do that? Can you advice me?

Saludos y gracias por el plugin.

There's a way to Reset the countedown timer

I want my countdown timer to reset itself and start again using the targetAchieved i've tried doing it like this:

timer.addEventListener('targetAchieved', function (e)
{
	timer.reset();
});

Got no results

How to Reset without Restarting?

I would like to reset the timer to 00:00:00 without restarting it until timer.start(); is called again. Is that possible?

Or maybe another way to ask, is how can I destroy the current timer instance and create a new one with an click event?

IE Support

I'm using the library on Internet Explorer, I'm having some problems. Does the Library support Internet Explorer?

startValues only works once

My timer looks like this: http://oi64.tinypic.com/vdeqeo.jpg

The set button is to allow the user to put a custom value and the timer starts from it. Here is the code:

    btnSet.addEventListener( "click", function () {

        let sec = Number( document.querySelector( '.sec' ).value );
        let min = Number( document.querySelector( '.min' ).value );
        let hour = Number( document.querySelector( '.hour' ).value );

        let config = {
            startValues: {
                seconds: sec,
                minutes: min,
                hours: hour
            }
        };

        timerInstance.start( config );
    } );

This works, but only once (and if i dont click on start button before). If i want to set the timer value more than 1x it doesn't work. What is the solution for this?

No Licence Issued with Repository

There is currently no licence associated with easytimer.js . This makes it legally impossible to use your software without written permission, as the default licence here as anywhere else is All Rights Reserved. Any software professional familiar with the issue will not touch your code with a ten foot pole.

I would like to use your library for an open source project, however, until such time as you give me written permission (in the form of a licence or not), I am unable to do so legally.

I suggest you visit Github's article on the matter. I chose GNU GPL v3.0, as I want my software to be shared-alike, but that's just me.

countup after countdown to 0

Hi,

Is there a proper way to start counting up immediately after counting down to 0?

What I have done is something like this.

timer.start({countdown: true, startValues: [0,3,0,0,0]});
timer.addEventListener('targetAchieved', function (e) {
  timer.stop();
  timer.start({
    countdown: false,
    startValues: [0,0,0,0,0],
    target: [0,0,0,0,1] // target is set to avoid targetAchieved event to be dispatched.
  });
});

Once countdown is done, target is set to 0 as a default and it is kept(can not be reset or set to null) even after start timer with countup.
I'm setting a target to avoid targetAchieved is dispatched every second and timer is started over again and again. But actually I don't want to set a target to countup timer.

Maybe I can achieve this with using two different timers(I haven't tried yet, though).
But still I think it'll be cool to be able to do it with using one timer.
What do you think? Or do you have any ideas?

Thanks.

Events every 60 seconds

Hi, I want to create a counter that every 60 seconds run an event but I have to start the counter at the click of a button.
And if in events the result is false, the counter stops
How can I proceed ?

Best Regards

startValues

is it possible to give second to easytimer for startValue
if we could so how should I do that???

store seconds in variable

  • Question

In my application, I want seconds in milliseconds.

Is there a way to get time in milliseconds?

Currently, I'm doing like

timer.addEventListener('secondsUpdated', function() {
    console.log(timer.getTimeValues().toString());          // working, printing 00:00:00
    console.log(timer.getTotalTimeValues().seconds);   // working, printing seconds: 1, 2, 3, 4, etc
    val time_spend_seconds = timer.getTotalTimeValues().seconds;  // giving error as: SyntaxError: unexpected token: identifier
    console.log(time_spend_seconds);                           // not reachable due to above error
    val time_milliseconds = time_spend_seconds * 1000;
    console.log(time_milliseconds);
});

startValues cannot be negative.

I would like my timer to start at -4 seconds.
Is this easy to implement?

this.timer.start({ precision: 'secondTenths', startValues: [0,-4,0,0,0] });

ES6 Imports?

Hey! Thanks for the package. For some reason when doing import * as Timer from 'easytimer.js'; I get the error File '/project/node_modules/easytimer.js/index.d.ts' is not a module.

Any idea how to fix that? If I can get it to compile, it appears it does actually work.

Pause button = resume function

Hello,

thanks for creating the great timer script!
I am aware of the "pause" button from your sample page, my problem is I only have 3 buttons. Start, Pause/Resume and Stop. The Pause button should resume the timer when clicked again after being paused.

I tried to change the class after the click on the pause button from "pauseButton" to "startButton" but this didn't help. Is there anyway to do this?

Here's my HTML:
<div id="controls" class="recordingTime"> <button id="recordButton" class="startButton" onclick="displayStopwatch()"><i class="fas fa-microphone"></i></button> <button id="pauseButton" class="pauseButton" disabled><i class="fas fa-pause"></i></button> <button id="stopButton" class="stopButton" disabled><i class="fas fa-stop"></i></button> </div>

That's my current timer code:
// show recording time var timer = new Timer(); $('.recordingTime .startButton').click(function () { timer.start(); }); $('.recordingTime .pauseButton').click(function () { timer.pause(); }); $('.recordingTime .stopButton').click(function () { timer.stop(); }); timer.addEventListener('secondsUpdated', function (e) { $('.recordingTime .values').html(timer.getTimeValues().toString()); }); timer.addEventListener('started', function (e) { $('.recordingTime .values').html(timer.getTimeValues().toString()); });

Pass component Id to event listener

Hi,

I'm creating a couple of timers inside for loop and I need to set each one of them to a single span tag but I can't pass the span id to set. Is there any way to do that?

Here is the code

  for (i = 0; i < 5; i++) {
                var timer = new Timer();
                var seconds = $("#time_diff_" + i).val();
                timer.start({precision: 'seconds', startValues: {seconds: seconds}});
                timer.addEventListener('secondsUpdated', function (e) {
                    $("#timer_" + i).html(timer.getTimeValues().toString(['minutes', 'seconds']));
                    if (timer.getTimeValues().minutes >= 15) {
                        $("#timer_" + i).removeClass("text-success").addClass("text-danger");
                    }
                });
            }

Multiple timers, each with a button

Hello, thanks for the help.

So on my page I have a list of multiple tasks and each task has a timer next to it.
I have been trying to "attach" each timer to it's task. The only problem is that I'm stuck at getting the correct time value to the right task.

If I use the function timer.getTimeValues(), it only takes the value of the first timer it can find.
Is it possible to make it so I can get the correct time values for each task?

The function of the eventListener is like this

	timer.addEventListener('secondsUpdated', function (e) {
		$('.task-status').each(function() {
			if($(this).hasClass('task-stop')) {
				$(this).parent().parent().find('.task-timer').html(timer.getTimeValues().toString());
			}
		});
	});

Thanks!

Adjust size of the Clock face

I was looking through the flipclock.css where I could adjust the size of the clock. I wish to make it small,

could you advise?

About clear

Hi everyone, somebody could tell me how can I clear the values of the timer to 00:00:00 again when click another button?

Thanks

Time slowing down when unfocused

Thanks for an awesome package! Unfortunately I'm experiencing some strange time slow-down when I focus away from the tab or browser window that easytimer is running in. I experience the same issue on your website. The countdown slows, but does not completely stop. Do you know why this could be?

How to integrate LocalStorage ?

How can we integrate localStorage to the timer? For example, I'd like to create a start/stop timer and pause the page whenever I leave..., then when returning to the page it remembers my value and resumes.

Would this be an easy integration ?

Thanks for a great plugin!

incomplete Event type

In the index.d.ts, the type of Event only lists a few possible values, which is inconsistent with the events written in README.

export type Event = 'daysUpdated' | 'hoursUpdated' | 'minutesUpdated' | 'secondsUpdated' | 'secondTenthsUpdated';

Countdown Mode, Wrong End date

I am using the v2.4.0 of the library since I am getting errors in the latest one. I've set the target date to 25 December 2018, I want it to countdown from current time.

var today = new Date();
var date = new Date('December 25, 2018');

var timer = new Timer();
timer.start({countdown:true, startValues:{days:today.getDay(),hours:today.getHours(), minutes:today.getMinutes(), seconds:today.getSeconds()}, target:{days:date.getDay(),hours:date.getHours(), minutes:date.getMinutes(), seconds:date.getSeconds()}});
timer.addEventListener('secondsUpdated', function (e) {
    $('#sale-countdown .days').html(timer.getTimeValues().days);
    $('#sale-countdown .hours').html(timer.getTimeValues().hours);
    $('#sale-countdown .minutes').html(timer.getTimeValues().minutes);
    $('#sale-countdown .seconds').html(timer.getTimeValues().seconds);
});

I am getting the wrong end date. What am I doing wrong?

The v3.0.0 was throwing a Timer() is not defined error BTW. Also, VS Code was showing an error in the min file.

Is there anyway to get the whole time in minutes?

Hello,

For example, once I started a timer and I only need the minutes and seconds if get those values using timer.toString(['minutes', 'seconds'] for the first 59 minutes it's OK but once it has past the first hour the minutes starts again. Basically I wonder if there is anyway to get the time past only in minutes

Example when it' 1:30:00 I'd like to get 90:00 (only minutes and seconds)

How to show days in hours?

Is it possible to show days in hours? or, the minute hand continue counting after 24 hours?

Example:

1d 14h 10m 12s = 38:10:12

jQuery.Deferred exception: Timer is not defined ReferenceError: Timer is not defined

In the input file to the webpack I am doing require('easytimer'); and doing so with jQuery in the main,js

$(function () {
    var timer = new Timer();
});
jQuery.Deferred exception: Timer is not defined ReferenceError: Timer is not defined
    at HTMLDocument.<anonymous> (...)
    at mightThrow (eval at <anonymous> (...all.js), <anonymous>: ...:...)
    at process (eval at <anonymous> (...all.js), <anonymous>:...:...) undefined 
Uncaught ReferenceError: Timer is not defined(anonymous function) @ main.js:...
mightThrow @ ?...:...process @ ?...:...
undefined


// WEBPACK FOOTER //
// 

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.