Coder Social home page Coder Social logo

severindk / moment-timer Goto Github PK

View Code? Open in Web Editor NEW
110.0 7.0 32.0 335 KB

Timer plugin for Moment.js that allows creation of setInterval and setTimeout-like timers.

License: MIT License

HTML 21.11% JavaScript 78.89%
timer moment-timer settimeout setinterval javascript-timer timeout interval moment duration

moment-timer's Introduction

moment-timer

NPM version NPM downloads MIT License


No Longer Maintained

As of 2024-04-04, this project, a plugin for moment.js, is no longer being actively maintained. The moment.js library itself has also ceased active maintenance. We strongly recommend users begin migrating to more actively supported libraries for future projects and maintenance needs.

If you're currently using this plugin, here's what you need to know:

  • No New Features or Bug Fixes: The project will not receive updates, new features, or bug fixes.
  • Read-Only: The repository has been archived, making it read-only. You can still fork it, but contributions, issues, and pull requests will not be accepted.

Thank you to all the contributors, users, and supporters who made this project possible over the years. Your support and contributions were invaluable, and we hope the project served your needs well during its time of activity.


Synopsis

This is a Moment.js plugin that allows the use of timers, which offer much more control than the native JavaScript timers. It's basically a rewrite of JavaScripts own setInterval and setTimeout. For an example, see the example folder or read the Usage section below.


Installation

Npm

npm install moment-timer

Bower

bower install moment-timer

CDN

<script src="https://cdn.jsdelivr.net/npm/moment-timer/lib/moment-timer.js"></script>

Browser

<script src="path/to/moment-timer.js"></script>

When using this plugin in the browser, be sure to include moment.js on your page first.


Attributes

(bool) start

new moment.duration(1000).timer({ start: true }, callback);

Setting this attribute to true will cause the timer to start once instantiated.


(bool) loop

new moment.duration(1000).timer({ loop: true }, callback);

Setting this attribute to true will cause the timer to loop/restart once a duration is complete.


(int | moment.duration) wait

new moment.duration(1000).timer({ wait: 5000 }, callback);
new moment.duration(1000).timer({ wait: moment.duration(5, 'seconds') }, callback);

Setting this attribute will cause the timer to wait for a specified amount of time before starting it's duration. This is kind of an extra first duration. Imagine a timer that runs every second. Setting the wait attribute to 5000 / 5 seconds, means it waits that long and then starts acting like a normal timer would. Notice that this attribute accepts both int and moment.duration .


(bool) executeAfterWait

new moment.duration(1000).timer({ wait: 5000, executeAfterWait: true }, callback);

Setting this attribute to true will cause the callback function to be called after the wait duration has ended. This is a way to make sure the callback is executed even before the timer starts.


Functions

.start()

let timer = new moment.duration(1000).timer(callback);
timer.start();

This function will cause the timer to start. It can be used if the start attribute has not been set or if the timer has been stopped.


.stop()

let timer = new moment.duration(1000).timer({ start: true }, callback);
timer.stop();

This function will cause the timer to stop. It can be used if timer has been started to halt it.


.duration(int | moment.duration)

let timer = new moment.duration(1000).timer(callback);
timer.duration(5000);
timer.duration(moment.duration(5, "seconds");

This function can be used to change the duration the timer was instantiated with.


.getDuration()

let timer = new moment.duration(1000).timer(callback);
timer.getDuration();

This function will return the current duration of a timer. In this case it will return 1000.


.getRemainingDuration()

let timer = new moment.duration(1000).timer(callback);
timer.getRemainingDuration();

This function will return the remaining duration of a timers cycle. In this case, imagine that the timer has been running for 500ms and we call .getRemainingDuration() on it, in this example it will return 500, since half of the cycle has completed.


.isStopped()

let timer = new moment.duration(1000).timer(callback);
timer.start();
timer.isStopped();  // false
timer.stop();
timer.isStopped();  // true

This function can be used to see if the timer has been stopped by the .stop() function.


.isStarted()

let timer = new moment.duration(1000).timer(callback);
timer.start();
timer.isStarted();  // true
timer.stop();
timer.isStarted();  // false

This function can be used to see if the timer has been started by the .start() function. If this function is called on a timer that has reached the end of it's duration and does not loop, it will also return false as if the timer has not yet been started.


Feel free to open a new issue or create a pull request if you can think of other useful attributes or functions.


Changelog

v1.3.1

Added nodejs example and increased minimum version of moment. See #26

v1.3.0

Fixed issue where .stop() would not stop the timer. See #20

v1.2.3

Relaxed moment dependency.

v1.2.2

Removed debug console.log

v1.2.1

Updated readme with better documentation and added a new isStarted function.

v1.2.0

Added module loading!

v1.1.5

Added getDuration and executeAfterWait attribute.

v1.1.4

Added isStopped function.

v1.1.3:

...

v1.1.2:

Fixed stop function. It still had an old unused paused variable instead of the new stopped variable. Fixing this will ensure that stopping and starting the timer will not cause any problems.

v1.1.1:

Cleaned up some things, fixed a remainingDuration bug and added an internal clearTimer function.

v1.1.0:

Changed setDuration to duration and added actual moment.duration support to it. Deprecated error message on setDuration will be removed in next release.

v1.0.0:

Initial Release.


Contributing

You are always welcome to contribute to this repository. Create your own branch, make the changes you wish to see and create a pull request that we can have a look at. If the changes make sense and the quality of code is good enough, then it will be merged into the master branch so other people can use it.

A full list of contributers for moment-timer.js can be found here.


License

Moment-timer.js is freely distributable under the terms of the MIT license.


moment-timer's People

Contributors

atefbb avatar justbill2020 avatar lukasdrgon avatar memborsky avatar mewm avatar seanparmelee avatar severindk avatar tourdefran 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

moment-timer's Issues

Eslint Issue in Require

There is eslint issue when assigning the moment-timer library to a variable.

timer = require('../node_modules/moment-timer/lib/moment-timer');
timetest = new moment.duration(1, 'minutes').timer(test);

This causes eslint to flag no-unused-vars on the timer variable as it doesn't believe it's being used.

Add a step callback to timer arguments

It would be nice to be able to configure a step function to be executed before the timer callback happens. This would make it easy to display a count down timer in html. Maybe something like this...

var redirectTimer = moment.duration(60, "seconds").timer({
    loop: false,
    start: true,
    step: { 
        delay: 1000, 
        callback: function(){ console.log("I've got " + redirectTimer.getRemainingDuration() + "ms left"); }
    }
}, function () {
    alert("times up");
});

Custom time zone + multiple timers + custom days

First of all let me thank you for this excellent plugin. It's very nice!

As the title says, I am in the need of something a bit more complex; and since I`m quite a noob in JS (never really like it to be honest) achieving this is painful.

Could you give me an example and tell me if this is possible at all:

  • Set desired time zone for the timers
  • Multiple timers started at the same time (so seconds lapse is the same for all)
  • Each timer to specify hour:minute:second
  • Each timer on callback to wait for a specified amount of time and display some text like "happening" before starting again
  • Customize each timer based on days, for example Timer1 runs on Monday and Tuesday only, Timer2 runs every day, Timer3 runs only Saturday (I hope I`m explaining right)

I`m having a play around meanwhile to see if I can do this, however I would really appreciate a bit of help :)

Thanks!

Can't stop timer

Hi!

Trying to stop timer once it runs out.

var realTimer;
  realTimer = moment.duration(5, 'seconds').timer({
    loop: false,
    start: true
  }, function () {
    console.log('timer cb');
    realTimer.stop();
    console.log(realTimer.isStopped()); // false
  });

Even tried to stop it like this:

setTimeout(function () {
    realTimer.stop();
    console.log(realTimer.isStopped()); // false
  }, 10000);

Timer not runs on start after delay

I use the following code to schedule execution of 'update' function

moment.duration(config.updateIntervalInSeconds, 'seconds').timer({wait: intervalToUpdate, loop: true }, update);

And I expect that first run of 'update' will be in 'intervalToUpdate' seconds.
But in reality the first run will be in 'config.updateIntervalInSeconds + intervalToUpdate' seconds.
I've looked to source and found the reason.

Here it is.

       if (this.loop) {
            this.timer = setInterval(function() {
                self.updateStartEndTickFromDuration(self.timerDuration);
                return self.callback();
            }, this.timerDuration);
        }

When setInterval is executed it is not run the callback.

I suggest following solution

       if (this.loop) {
            self.callback();
            this.timer = setInterval(function() {
                self.updateStartEndTickFromDuration(self.timerDuration);
                return self.callback();
            }, this.timerDuration);
        }

To call self.callback() manually.
What do you think?

Test suite failed to run

I am trying to write test for my React Component by using jest. I wrote a mock for moment like this

const moment = require.requireActual('moment');

export default (timestamp = 0) => {
  return moment(timestamp);
}

what I get from console is

Test suite failed to run

    TypeError: Cannot read property 'fn' of undefined

      at node_modules/moment-timer/lib/moment-timer.js:160:21

usage of moment timer in my React component

const timeTicker = new moment.duration(1000).timer(
      { start: true, loop: true },
      this.updateTimeHandler
    );

and my test

import React from "react";
import { configure, shallow } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import renderer from "react-test-renderer";

import Timer from "./Timer";


configure({ adapter: new Adapter() });

beforeAll(() => {
  
});

describe('<Timer />', () => {
  let wrapper;

  beforeEach(() => {
    wrapper = shallow(<Timer />)
  })


})

duration not defined

var timer = moment.duration(5, "seconds").timer({
^

TypeError: Cannot read property 'duration' of undefined
at Object. (C:\Users\SkullNull\Desktop\abcde\timer.js:2:19)
at Module._compile (module.js:573:30)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Function.Module.runMain (module.js:609:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:598:3

executeAfterWait requires a wait period

I know that it's probably WAI, but I end up with a lot of situations where I need to execute a function now, and then every x seconds after. The only way right now to do this in moment-timer is to set a wait period of one millisecond, because the constructor checks for the wait period being greater than zero when handling executeAfterWait.

Suggestion: replace

if (attributes.wait > 0) {
	var self = this;
	setTimeout(function () {
		if (attributes.executeAfterWait) {
			callback();
		}
		self.start();
	}, attributes.wait);
} else {
	this.start();
}

with

if (attributes.executeAfterWait) {
	if (attributes.wait > 0) {
		var self = this;
		setTimeout(function () {
			callback();
			self.start();
		}, attributes.wait);
	} else {
		callback();
		this.start();
	}
} else {
	this.start();
}

or similar. Alternatively, timeouts can be set with a period of 0 which executes immediately, allowing that specific check to become (attributes.wait || 0) >= 0 instead, to allow for null to act as zero in event that no wait period was listed.

Seems to repeatedly call callback if it returns false

I have the following implemented:

            TICKTOCK[mkr.ASSET_TAG] = moment.duration(CONFIG.setting('APP.UPDATE_FREQUENCY_X_SECS'), 'seconds').timer(
                {
                    loop: true
                },
                function() {
                    updateMarkers();
                }
            );



   let updateMarkers = function() {
        if (!Scope.isUpdating) {
            Scope.isUpdating = true;
            console.log('Updating map');
            $def = $.Deferred;

            $.ajax(
                {
                    url: CONFIG.setting('ENDPOINTS.UPDATE_MAP'),
                    data: {},
                    dataType: 'json',
                    type: 'GET',
                    success: function(response) {
                        if (response.status) {
                            var data = response.data;

                            for (device in data) {
                                var assetTag = data[device].device.asset_tag;
                                var coords   = data[device].locations.shift();
                                var lat      = coords.normalized_lat;
                                var lng      = coords.normalized_lng;
                                setMarker(assetTag, lat, lng);
                            }

                        }
                    },
                    complete: function(xhr, status) {
                        Scope.isUpdating = false;
                    },
                    error: function(xhr, status, error) {
                        alert('An error occurred while updating the map');
                    }
                }
            );
            return true;
        }
        return false;
    };

However, if that callback at the bottom returns false, the function seems to get called infinitely. Is this expected behavior?

Thanks!

ES6 Import

Hi thanks for building this amazing plugin!

Right now I'm having an issue where I try to import this using Browserify with the ES2015 preset and the plugin is not registering with moment.

This currently doesn't work

import moment from 'moment'
import 'moment-timer'

This throws a TypeError

var timer  moment.duration(1, 'seconds').timer()

Uncaught TypeError: _moment2.default.duration(...).timer is not a function

I'm using React as well

Thanks!

ReferenceError: callback is not defined

I'm using moment-timer for a server based in node js.

This is how I'm calling the packeges.

var moment = require('moment'); moment().format(); var moment = require('moment-timer');

When I try to run the timer, this error appears.

let timer = new moment.duration(1000).timer(callback); ReferenceError: callback is not defined

timer.stop() is not working as expected

Hi, great Moment plugin!
Sadly I'm having an issue, probably related to the stop() method.

Sometimes it wont stop when the method is called and keeps looping, I'm using RequireJs and VelocityJs for some animations, I spent my last day debugging this, any help will be appreciated

I have uploaded a sample to test it
The play button starts the timer, and the stop should stop it, in the console I print the isStopped() status
sometimes brings false, and sometimes works,
thanks in advance,
Fran

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.