jQuery Timer: Start/Stop/Resume/Remove pretty timer inside any HTML element.

Overview

jQuery Timer plugin

  • Lightweight, well tested Build Status jQuery pretty timer plugin
  • Start, Pause, Resume and Remove a timer inside any HTML element.
  • Get notified after specific time or at regular intervals.
  • Click and edit time while timer is running!
  • Enable multiple timers on the same page.

Demo & Instructions | Download

Getting started

Load the plugin in a script tag (right after loading jQuery) directly from CDNjs using this URL,

https://cdnjs.cloudflare.com/ajax/libs/timer.jquery/0.7.0/timer.jquery.js

If you are using bower,

bower install timer.jquery

Alternatively you can download the jQuery timer plugin and host it relative to your HTML file. Once you have your preferred way to get jquery and the timer plugin, in your web page:

<script src="path/to/jquery.js"></script>
<script src="path/to/timer.jquery.js"></script>
<script>
(function($) {

  //start a timer
  $("#div-id").timer();

}());
</script>

Usage

To start a timer with options:

$("#div-id").timer(options);

Options for timer:

$("#div-id").timer({
	seconds:	{Int},		// The number of seconds to start the timer from
	duration: 	{String},	// The time to countdown from. `seconds` and `duration` are mutually exclusive
	callback: 	{Function},	// If duration is set, this function is called after `duration` has elapsed
	repeat: 	{Bool},		// If duration is set, `callback` will be called repeatedly
	format:		{String},	// Format to show time in
	editable:	{Bool}		// If click and edit time is enabled
	hidden;		{Bool}		// If true, the timer is not displayed in the selected item.
});

Methods available on an initialized timer:

//pause an existing timer
$("#div-id").timer('pause');

//resume a paused timer
$("#div-id").timer('resume');

//remove an existing timer
$("#div-id").timer('remove');  //leaves the display intact

//get elapsed time in seconds
$("#div-id").data('seconds');

Timed Events

Start a timer and execute a function after a certain duration. You can use this to simulate a timed event.

//start a timer & execute a function in 5 minutes & 30 seconds
$('#div-id').timer({
	duration: '5m30s',
	callback: function() {
		alert('Time up!');
	}
});

Start a timer and execute a function repeatedly at a certain duration.

//start a timer & execute a function every 2 minutes
$('#div-id').timer({
	duration: '2m',
	callback: function() {
		console.log('Why, Hello there');	//you could have a ajax call here instead
	},
	repeat: true //repeatedly calls the callback you specify
});

Start a timer and execute a function repeatedly at a certain duration and then reset the timer.

//start a timer & execute a function every 2 minutes
$('#div-id').timer({
	duration: '2m',
	callback: function() {
		$('#div-id').timer('reset');
	},
	repeat: true //repeatedly calls the callback you specify
});

Timer state

You can get the current state of timer by querying the state property on it's data object

$('#div-id').data('state'); 	// running | paused | stopped | removed
Duration Syntax

When you initialize a timer with the duration and callback parameters, the timer plugin executes the callback function at the set duration. The syntax for specifying the duration is verbose. h for hours. m for minutes and s for seconds. Here are some examples:

'3h15m'		// 3 hours, 15 minutes
'15m'		// 15 minutes
'30s'		// 30 seconds
'2m30s'		// 2 minutes 30 seconds
'2h15m30s'	// 2 hours 15 minutes and 30 seconds
Format Syntax

By default the timer displays the biggest whole unit. Examples:

  • seconds: 50 will show as 50 sec
  • seconds: 63 will show as 1:03 min
  • seconds: 3663 will show as 1:01:03

If you want to customize the format in which the timer displays time, use the format option. Available formats the timer understands are:

Format Description Example
%h Non-zero padded Hours %h hours gives 3 hours
%m Non-zero padded Minutes unless number of minutes is greater than 60 %h:%m minutes gives 0:6 minutes or 1:06 minutes
%g Non-zero padded Total Minutes Irrelative to hours %G minutes gives 75 minutes or 6 minutes
%s Non-zero padded Seconds unless number of seconds is greater than 60 %h:%m:%s gives 0:0:6 or 0:1:06 or 1:01:06
%t Non-zero padded Total Seconds Irrelative to minutes and hours %t gives 3660 or '9'
%H Zero padded Hours %H hours gives 03 hours
%M Zero padded Minutes %H:%M minutes gives 00:06 minutes
%G Zero padded Total Minutes Irrelative to hours %G minutes gives 75 minutes
%S Zero padded Seconds %H:%M:%S gives 00:00:06
%T Zero padded Total Seconds Irrelative to minutes and hours %T gives 3660

Countdown

You can use the jQuery timer plugin for countdown as well.

$('#timerDiv').timer({
    countdown: true,
    duration: '3m40s',    	// This will start the countdown from 3 mins 40 seconds
    callback: function() {	// This will execute after the duration has elapsed
    	console.log('Time up!');
    }
});
Comments
  • Multiple Timers

    Multiple Timers

    Nice plugin! I'm trying to wrap my head around it - I'm using it in a project but whenever I add multiple timers to a page, they WORK, however, only one works at a time - and its like the plugin can't keep track of more than one timer at a time

    any way to make it work with multiple instances? It looks like its setup to in the plugin code its just not working and can't figure out why!

    Thanks for your time and help! :+1:

    enhancement 
    opened by andysowards 14
  • Pause functionality not working for all timers

    Pause functionality not working for all timers

    Hi guys,

    Firstly - great script, I'm using it within PhoneGap to create my first basic test app and it's proving very useful.

    I am creating a simple timer on one screen where we have 3 simultaneous timers:

    1. Elapsed - counts up to a set interval duration (e.g. 20s first, then 10s, then 30s)
    2. TotalTime - counts up, will cover multiple intervals (e.g. 1 min in this simple case)
    3. Remaining - is a countdown timer from the total of all intervals (e.g. 1 min in this simple case)

    Lets ignore the complexities around refreshing the Elapsed timer for each interval and getting the total time for the countdown for the moment.

    I start all timers simultaneously using $('#Go').click - assuming this is all I do the counters work well.

    I have a pause button triggered by $('#Pause').click which then pauses all the timers at whatever reading they were on using the following code:

    $('#Pause').click(function() { // Now need to pause the timers $('#Elapsed').timer('pause'); $('#TotalTime').timer('pause'); $('#Remaining').timer('pause');

    • some other unrelated code }); // End Pause click

    When I resume the timers however Elapsed seems to work as intended, but the other two timers jump out of sync - e.g. I have a demo running in the background just now which is meant to last 30s but TotalTime is 6:55 and Remaining is -7:25.

    I tried flashing an alert when paused to confirm the state of the timers and they all do return "paused" as I would expect so I think I'm implementing it properly.

    I noted that there was a closed case for a similar issue which you corrected with the latest version - I tried replacing the script with that one but the problem persisted (and actually created a new one whereby there is a slight delay starting the timers which knocks some other stuff out.)

    Would you be able to advise whether this is a script issue or a user issue? Would be great to get this resolved as I can finally close off that piece of my app :)

    Many thanks Wayne

    opened by wgpalexander 9
  • Publish as WebJar

    Publish as WebJar

    Please publish the latest library version as WebJar. So it will be easily accessible from Gradle or Maven in Java projects (and in Scala, Kotlin, Groovy as well).

    I think it's a good way to deploy the timer.jquery library.

    Example: The Final Countdown (Github) is available at Maven Central.

    need-help 
    opened by naXa777 4
  • Get %H %M %S

    Get %H %M %S

    Hi, great plugin :)

    Is there anyway to display the time in h m s rather than just displaying total seconds elapsed when using $('#sampleid').data('seconds'); ?

    opened by keshiabrown16 4
  • Options being duplicated between different instances of timer

    Options being duplicated between different instances of timer

    There appears to be an issue when creating multiple timers, where the "options" from the last instantiated timer, override the values for the previous timers. The most obvious example of this can be seen in the callback or format. In the example below, I have two divs, with the id's of timerTest1 & timerTest2.

                $("#timerTest1").timer({
                    duration: '3s',
                    format: '%H:%M:%S',
                    callback: function () {
                        $("#timerTest1").css("color", "red");
                        alert("This is the timerTest1 callback");
                    }
                });
                $("#timerTest2").timer({
                    duration: '5s',
                    format: '%M:%S',
                    callback: function () {
                        $("#timerTest2").css("color", "green");
                        alert("This is the timerTest2 callback");
                    }
                });
    

    From digging through the source, it appears that in the "TIMER PROTOTYPE" section, the options object always has the values of the last iteration.

    Sample file: test.txt

    opened by IanCaz 4
  • Unexpected behavior on timer focus/blur

    Unexpected behavior on timer focus/blur

    Plugin does not recognize intentional and unintentional focus and blur events.

    For example.

    1. I pressed "Start" button.
    2. I pressed "Stop" button.
    3. Focus on timer input field and change value.
    4. Switch focus away from timer input field.
    5. Timer will unexpectedly start. It shouldn't since we stopped it in step 2.
    enhancement 
    opened by elaman 4
  • Customise display so you can show the clock in format hh:mm:ss (or just mm:ss)

    Customise display so you can show the clock in format hh:mm:ss (or just mm:ss)

    Can someone help please - I would like to customise the display so the hh:mm:ss (or just mm:ss) are always displayed ie 00:00. I would also like to hide the sec or min text that is appended to the clock display Any help would be really appreciated

    opened by TryHardDev 4
  • Causing an Undefined error

    Causing an Undefined error

    The error has been fixed by adding the jQuery selector '$' as you can see below.

    /! timer.jquery 0.7.0 2017-04-15/ (function($) { ... rest of the code ... } (jQuery));

    opened by omelsoft 3
  • Automatically change to hour format display via callback

    Automatically change to hour format display via callback

    Hello! :smile:

    Thanks for your great work. I need to change the timer to "%H:%M:%S" format when it reached 59:59. So far I was able to do it but not sure if this is how you'd prefer to be doing it... if yes, then it would be helpful to others if something like this is also added in the documentation examples. If no :smile: I'd be cool if you share your way of doing it. :smile:

    var callDuration = $('#call-duration');
    
    callDuration.timer({
        duration: '61s', //since 3599 is divisible by 59 or 61
        seconds: 3590, //simulation purposes
        format: '%M:%S',
        callback: function() {
    
            var total = callDuration.data('seconds');
    
            if(total === 3599) { //change to hour format (3600 - 1 to prevent display bug)
                this.format = '%H:%M:%S';
            }
        },
        repeat: true //repeatedly call the callback
    });
    
    opened by arvi 3
  • 你的timer.jquery插件有个问题...Your  timer.jquery  js have a bug...

    你的timer.jquery插件有个问题...Your timer.jquery js have a bug...

    您好,首先我很抱歉不太会讲英语,我在项目中使用你的timer.jquery,发现有个问题,在手机下不支持"Object.assign",我把它换成"$.extend"就好了。 HI,First I'm sorry I don't speak English,I use your timer.jquery for my project, In the mobile browser not support "Object.assign", Me replace "$.extend" it's ok.

    opened by huangxinliu 3
  • Unexpected token import

    Unexpected token import

    I am trying to use this plugin..But it throws me this error in the console:

    "Uncaught SyntaxError: Unexpected token import" @ line 2 in Timer.js

    I don't know whats wrong...

    I don't have a very specific or different working tree...

    Project/ ├── action │   ├── CommonAction.php │   ├── DAO │   │   ├── Connection.php │   │   ├── dbInfo.php │   │   └── UserDAO.php │   └── IndexAction.php ├── index.php ├── js │   ├── constants.js │   ├── index.js │   ├── Timer.js │   ├── util.js │   └── utils.js └── stylesheets └── style.css

    Some help would be cool :D

    opened by lemonbuzz 3
  • countdown timer shows negative time.

    countdown timer shows negative time.

    Hi,

    I have an issue where the timer shows negative time and callback is not called when the mobile screen is locked. When screen is unlocked how to make sure that the timer stops at 0 and doesn't display negative values. Below is my config.

        var totalSeconds = 20;
        $("#t").timer({
            action: 'start',
            duration: totalSeconds,
            countdown: true,
            callback: function () {
                location.reload();
            }
        });
    

    Regards, Bhavana C

    opened by bhavanac24 0
  • how to write the script two functions

    how to write the script two functions

    Dear Sir/Madam,

    how to write the script two functions, such as start a timer & execute a function in 5 minutes & 30 seconds and also execute a function every 2 minutes ? is it true like below :

    $('#div-id').timer({ duration: '5m30s', callback: function() { alert('Time up!'); } });

    $('#div-id').timer({ duration: '2m', callback: function() { console.log('Why, Hello there'); }, repeat: true });

    Thanks in advance Regards,

    Arief

    opened by ariefwiryanto 0
  • The callback function is never executed

    The callback function is never executed

    $that.timer({
        duration: "10s",
        format: "%ss",
        countdown: true,
        callback: function() {
            console.log('Time up!');
        }
    });
    
    opened by wwh447 0
  • Timer Greater than 24 Hours

    Timer Greater than 24 Hours

    I have created a tasks with timer, so if a person keep working for a task is greater than 24 hours then i have to show the 25th, 26th, ... and so on, I'm only keeping the hours for a task, I don't keep the days and hours, Can someone guide me how to achieve this, because right now if the time is 23:59;59 after 1 seconds i can see 00:00:01, it get reset again.

    opened by tahirafridi 1
  • hidden property not working

    hidden property not working

    The documentation clearly state that there should be a hidden property:

    $("#div-id").timer({
    	seconds:	{Int},		// The number of seconds to start the timer from
    	duration: 	{String},	// The time to countdown from. `seconds` and `duration` are mutually exclusive
    	callback: 	{Function},	// If duration is set, this function is called after `duration` has elapsed
    	repeat: 	{Bool},		// If duration is set, `callback` will be called repeatedly
    	format:		{String},	// Format to show time in
    	editable:	{Bool}		// If click and edit time is enabled
    	hidden;		{Bool}		// If true, the timer is not displayed in the selected item.
    });
    

    But in the code, there's nothing about it:

    function getDefaultConfig() {
    	return {
    		seconds: 0,					// Default seconds value to start timer from
    		editable: false,			// Allow making changes to the time by clicking on it
    		duration: null,				// Duration to run callback after
    		callback: function() {		// Default callback to run after elapsed duration
    			console.log('Time up!');
    		},
    		repeat: false,				// This will repeat callback every n times duration is elapsed
    		countdown: false,			// If true, this will render the timer as a countdown (must have duration)
    		format: null,				// This sets the format in which the time will be printed
    		updateFrequency: 500		// How often should timer display update
    	};
    }
    

    Also there's a few typos in the documentation, missing a comma and replacing ; by :, so it should be:

    	editable:	{Bool},		// If click and edit time is enabled
    	hidden:		{Bool}		// If true, the timer is not displayed in the selected item.
    
    
    opened by Zurd 3
Owner
Walmik Deshpande
JS@PayPal by day, Scribbletune by night
Walmik Deshpande
Countdown - jQuery CountDown Clock - Simple countdown plugin for product special offers

TronLink Wallet Address TRX - BTC - BTT - USDT: TH9RyofE7WiDDVVFLMJgFns2ByBRmgQzNB jQuery Countdown Clock jQuery countdown plugin that accounts for ti

E-Piksel 33 Aug 30, 2022
Nepali Date Picker jQuery Plugin 🇳🇵

Nepali Date Picker Nepali Date Picker jQuery Plugin for everyone. ???? Installation npm install nepali-date-picker Demo and Documentation https://leap

Leapfrog Technology 70 Sep 29, 2022
jQuery plugin to allow dragging and dropping of elements and sorting of lists and other nested structures.

Drag and Drop Basic jQuery plugin to allow drag and drop: dragging dropping of dragged elements sorting of lists and other nested html structures (ul,

Ole Trenner 12 Aug 26, 2021
Create Persian Calendar as html helper with tag builder c# , and convert selected persian date to gregorian date

Persian-Calendar Use JS,Html,CSS,C# White theme for Persian Calendar , easy to use. Create Persian Calendar as html helper. Use Tag builder in c# for

Tareq Awwad 4 Feb 28, 2022
null 3.9k Dec 30, 2022
Pretty-print-json - 🦋 Pretty-print JSON data into HTML to indent and colorize (written in TypeScript)

pretty-print-json Pretty-print JSON data into HTML to indent and colorize (written in TypeScript) 1) Try It Out Interactive online tool to format JSON

Center Key 87 Dec 30, 2022
基于vue3.0-ts-Element集成的简洁/实用后台模板!《带预览地址》vue-admin;vue+admin;vue-element;vue+element;vue后台管理;vue3.0-admin;vue3.0-element。

一、基于vue3.0+ts+Element通用后台admin模板 二、在线预览地址:http://admin.yknba.cn/ 三、下载使用: 1、克隆代码 通过git将代码克隆到本地;或者使用下载安装包模式进行下载。 2、进入目录 进入项目的根目录:vue3.0-ts-admin 3、安装依

null 64 Dec 16, 2022
A Node.js HTTP proxy that tracks managed PaaS account applications and auto-stop&start them

paastis-engine Features Paastis engine is the heart of the Paastis project. Its goal is to monitor and manage (start & stop) PaaS applications based o

null 14 Nov 8, 2022
A tiny JavaScript library to easily toggle the state of any HTML element in any contexts, and create UI components in no time.

A tiny JavaScript library to easily toggle the state of any HTML element in any contexts, and create UI components in no time. Dropdown, navigation bu

Matthieu Bué 277 Nov 25, 2022
A simple jQuery extension to make any HTML element sticky on scroll.

jquery.sticky.js A simple jQuery extension to make any HTML element sticky on scroll. Installation Just download the script and include it in your HTM

Achal Jain 2 Aug 22, 2022
An open source community powered Discord bot to stop and remove the trash from the SW workshop.

SW Anti Reuploads & Trash Discord bot An open source community powered Discord bot to stop and remove the trash from the SW workshop. SW Discord · Cre

SIMPLE MARK 4 Jun 20, 2022
Nest multiple blocks inside lists of any kind of list (ordered, unordered, no marker, etc), or do away with list markers and use it like a repeater!

Nest multiple blocks inside lists of any kind of list (ordered, unordered, no marker, etc), or do away with list markers and use it like a repeater!

Rani 15 Dec 26, 2022
Wrap a function with bun-livereload to automatically reload any imports inside the function the next time it is called

bun-livereload Wrap a function with bun-livereload to automatically reload any imports inside the function the next time it is called. import liveRelo

Jarred Sumner 19 Dec 19, 2022
ForgJs is a javascript lightweight object validator. Go check the Quick start section and start coding with love

Hey every one im really happy that this repo reached this many stars ?? ,but this repo needs your contibution I started to better document the code th

Hamdaoui Oussama 1.7k Dec 21, 2022
An example repository on how to start building graph applications on streaming data. Just clone and start building 💻 💪

Example Streaming App ?? ?? This repository serves as a point of reference when developing a streaming application with Memgraph and a message broker

Memgraph 40 Dec 20, 2022
A jQuery plugin that creates a countdown timer in years, months, days, hours and seconds in the form a bunch of rotating 3d cubes

CountdownCube is a jQuery plugin that is in the form of a bunch of rotating 3D cubes. It uses CSS transitions to create the 3D rotating cube effects.

null 16 Mar 6, 2022
A simple lightweight file dropzone component based on jQuery. You can easily make any existing element become a dropzone that holds files.

file-dropzone A simple lightweight file dropzone component based on jQuery. You can easily make any existing element become a dropzone that holds file

Anton Bardov 1 May 31, 2021
adds the *scrollin* and *scrollout* events to jquery, which will fire when any given element becomes (respectively) visible and invisible in the browser viewpori

jQuery.scrolling This plugin adds the scrollin and scrollout events to jquery: these events will fire when any given element becomes visible/invisible

Dark 5 Apr 7, 2021
Little Alpine.js plugin to add a typewriter effect to any HTML element.

⌨️ Alpine Typewriter ⌨️ An Alpine.js plugin to add a typewriter effect to any HTML element. ?? Installation CDN Include the following <script> tag in

Marc Reichel 58 Dec 28, 2022
Pretty diff to html javascript library (diff2html)

diff2html diff2html generates pretty HTML diffs from git diff or unified diff output. Table of Contents Features Online Example Distributions Usage Di

Rodrigo Fernandes 2.3k Dec 31, 2022