showing several timers in javascript - javascript

I'm tring to show several timers in asp.net page using javascript with different intervals , but all timers run with last set interval , how can I do this ?
here is the code I used :
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function _timer(callback)
{
var time = 4500;
var mode = 1;
var status = 0;
var timer_id;
var sor;
// this will start the timer ex. start the timer with 1 second interval timer.start(1000)
this.start = function(interval)
{
interval = (typeof(interval) !== 'undefined') ? interval : 1000;
if(status == 0)
{
status = 1;
timer_id = setInterval(function()
{
switch(mode)
{
default:
if(time)
{
time--;
generateTime();
if(typeof(callback) === 'function') callback(time);
}
break;
case 1:
if(time < 86400)
{
time++;
generateTime();
if(typeof(callback) === 'function') callback(time);
}
break;
}
}, interval);
}
}
// Same as the name, this will stop or pause the timer ex. timer.stop()
this.stop = function()
{
if(status == 1)
{
status = 0;
clearInterval(timer_id);
}
}
// Reset the timer to zero or reset it to your own custom time ex. reset to zero second timer.reset(0)
this.reset = function(sec)
{
// sec = (typeof(sec) !== 'undefined') ? sec : 0;
// time = sec;
generateTime(time);
}
// Change the mode of the timer, count-up (1) or countdown (0)
this.mode = function(tmode)
{
mode = tmode;
}
// This methode return the current value of the timer
this.getTime = function()
{
return time;
}
// This methode return the current mode of the timer count-up (1) or countdown (0)
this.getMode = function()
{
return mode;
}
// This methode return the status of the timer running (1) or stoped (1)
this.getStatus
{
return status;
}
// This methode will render the time variable to hour:minute:second format
function generateTime()
{
var second = time ;
//var minute = Math.floor(time / 60) % 60;
// var hour = Math.floor(time / 3600) % 60;
second = (second < 10) ? '0'+second : second;
// minute = (minute < 10) ? '0'+minute : minute;
// hour = (hour < 10) ? '0'+hour : hour;
$('div.timer span.second').html(second);
$('div.timer1 span.second').html(second);
// $('div.timer span.minute').html(minute);
// $('div.timer span.hour').html(hour);
}
}
// example use
var timer;
$(document).ready(function(e)
{
timer = new _timer
(
function(time)
{
}
);
timer.reset(110);
});
var timer1;
$(document).ready(function(e)
{
timer1 = new _timer
(
function(time)
{
}
);
timer1.reset(110);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server" >
<div class="timer">
<span class="second">1111</span>
</div>
<div>
<script type="text/javascript">
window.onload = function () { timer.start(806); };
</script>
</div>
</asp:Panel>
<asp:Panel ID="Panel2" runat="server" >
<div class="timer1">
<span class="second">2222</span>
</div>
<div>
<script type="text/javascript">
window.onload = function () { timer1.start(20); };
</script>
</div>
</asp:Panel>
<asp:Literal ID="Literal1" runat="server"></asp:Literal></div>
</form>
</body>
</html>
in this code , I have called the timer 2 times with different intervals but its just run with the last interval value .

Unless I'm missing something, it looks like it's just because you're setting the two values in both timers with:
$('div.timer span.second').html(second);
$('div.timer1 span.second').html(second);
Instead pass the selector into the constructor like so:
function _timer(selector, callback) {
Then change your visual updates to:
$(selector + ' span.second').html(second);
And new up your timers like:
timer = new _timer
(
".timer",
function(time)
{
...
and:
timer1 = new _timer
(
".timer1",
function(time)
{
...
Edit: I went back & looked... the reason only one timer is actually running is because you're using window.onload to setup the start calls, so the second one is simply replacing the first. Without completely changing your code, the easiest solution to fix this specific issue is to use jQuery to attach your load events (since jQuery allows adding multiple event handlers out of the box):
$(window).load(function () { timer.start(806); });
and
$(window).load(function () { timer1.start(20); });

Related

Enqueue function to execute after currently running function is done executing (setTimeout)

I have a basic timer where a user puts in a number, then it counts down until it hits 0.
I want the user to put another number while the timer for the prev is still going on. When the timer for the prev number hits 0, a new timer for the recently entered number will begin. My code somehow has both timers running concurrently despite my uses of setInterval and setTimeout.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<script>
var isRunning = false;
var qNums = [];
var wrapFunction = function (fn, context, params) {
return function () {
fn.apply(context, params);
};
};
function q() {
var sec = document.getElementById("data").value;
if (!Number.isInteger(parseInt(sec))) {
document.getElementById("timer").innerHTML = "Not a number!";
return;
} else if (parseInt(sec) < 0) {
document.getElementById("timer").innerHTML = "Invalid timer setting!";
return;
}
qNums.push(wrapFunction(countDown, this, [sec]));
while (qNums) {
qNums.shift()();
}
}
function countDown(sec) {
var sec = document.getElementById("data").value;
var ms = 100;
isRunning = true;
document.getElementById("timer").innerHTML = "";
document.getElementById("btn").innerHTML = "Ticking!";
var interval = setInterval(function () {
if (ms == 100) {
document.getElementById("timer").innerHTML = sec + ".00";
} else {
document.getElementById("timer").innerHTML = sec + "." + ms;
}
ms -= 10;
if (ms < 0) {
sec--;
ms = 100;
}
if (sec < 0) {
document.getElementById("data").value = "";
document.getElementById("btn").innerHTML = "Start";
document.getElementById("timer").innerHTML = "Countdown complete";
isRunning = false;
clearInterval(interval);
}
}, 100);
}
</script>
<body>
<h1>Timer</h1>
<label>Timer Duration: </label><input id="data" />
<button id="btn" onclick="countDown()">Start</button>
<p id="timer"></p>
</body>
</html>
q() is my awful attempt at trying to implement this. countDown() is the standalone implementation of the countdown, separate from this functionality.
EDIT: Why does the snippet not run my code but the browser does???? Not sure how to fix this
Good try, but each interval has no way of triggering the next one to start with a callback, and without that, they'll all run concurrently. Pass the q.shift()() in as a callback to the timer function which can be invoked when the timer runs out alongside clearTimeout, or write a loop and only run the 0-th timer if it exists.
Another problem: setTimeout is often mistaken to be perfectly accurate, but this is an incorrect assumption. The ms parameter only guarantees the timer will be invoked no sooner than the duration specified. The consequence of this is that it will accumulate drift. A more accurate approach is to use a date object to check the system's time.
Here's a proof-of-concept using the polling version:
const enqueueTimer = () => {
const sec = +els.data.value;
if (!Number.isInteger(sec)) {
els.timer.innerHTML = "Not a number!";
}
else if (sec < 0) {
els.timer.innerHTML = "Invalid timer setting!";
}
else {
timers.push({duration: sec * 1000});
}
};
const updateTimers = () => {
if (!timers.length) {
return;
}
const {duration, start} = timers[0];
const now = new Date();
if (!start) {
timers[0].start = now;
}
const elapsed = now - start || 0;
const remaining = duration - elapsed || 0;
const sec = remaining / 1000;
const ms = remaining % 1000;
els.timer.innerHTML = `${~~sec}.${("" + ms)
.slice(0, 2).padEnd(2)}`;
els.btn.innerHTML = "Ticking!";
if (elapsed >= duration) {
timers.shift();
if (timers.length) {
timers[0].start = new Date(start.getTime() + duration);
}
else {
els.data.value = "";
els.btn.innerHTML = "Start";
els.timer.innerHTML = "Countdown complete";
}
}
};
const els = {
btn: document.getElementById("btn"),
data: document.getElementById("data"),
timer: document.getElementById("timer"),
};
els.btn.addEventListener("click", enqueueTimer);
const timers = [];
setInterval(updateTimers, 100);
<h1>Timer</h1>
<label>Timer Duration: <input id="data" /></label>
<button id="btn">Start</button>
<p id="timer"></p>
If it bothers you that the interval always runs, feel free to save the interval id, add a clearInterval() on the id when all the timers expire and kick off a new interval when a fresh timer is created.

In a jsf web application, a Javascript based session timer works on Chrome but not on IE

In a jsf web application based on Seam and Richfaces, I ran into a problem concerning different browsers. The code (and every variation I tried) works flawless in Chrome, but not in Internet Explorer (I am testing version 11).
The code is supposed to start and display a session-timeout countdown in the header. In the beginning of the template file, the timeout is retrieved from the application preferences and stored in a hidden field. The countdown timer is reset whenever a new page is loaded, or when an AJAX request is triggered (resetInactivityTimer()).
I am having 2 problems in IE:
It seems that the window.onloadfunction is not triggered on IE. The counter starts working fine when triggered manually in the console.
When the counter is started manually, an error occurs when an AJAX request is triggered.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Title</title>
<link rel="shortcut icon" type="image/x-icon" href="#{facesContext.externalContext.requestContextPath}/img/favicon.ico" />
<a:loadStyle src="/stylesheet/theme.css" />
<ui:insert name="head" />
</head>
<body>
<h:inputHidden id="originalTimeoutId" value="#{preferencesManager.getPreferenceValue(Preference.HTTP_SESSION_TIMEOUT)}"/>
<a:loadScript src="/scripts/script.js"/>
<a:region id="status_zone">
<a:status for="status_zone" forceId="false" id="ajaxStatus" onstart="resetInactivityTimer()">
<f:facet name="start">
<h:panelGroup>
<div style="position: absolute; left: 50%; top: 50%; text-align:center; width: 100%; margin-left: -50%;z-index: 10001;" >
<h:graphicImage value="/img/wait.gif"/>
</div>
<rich:spacer width="95%" height="95%" style="position: absolute; z-index: 10000; cusor: wait;" />
</h:panelGroup>
</f:facet>
</a:status>
<div class="main">
<ui:include src="/layout/header.xhtml" />
<ui:include src="/layout/menu.xhtml" />
<div style="margin-top: 10px;">
<ui:insert name="body" />
</div>
<ui:include src="/layout/footer.xhtml" />
</div>
</a:region>
<script type="text/javascript">
window.onload = initCountdown();
</script>
</body>
</html>
The countdown timer is displayed in the top right corner in the Header file "header.xhtml", which is loaded in the template, and therefore contained on every page:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:s="http://jboss.com/products/seam/taglib"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<div class="header">
<s:graphicImage value="#{preferencesManager.getPreferenceByteContent(Preference.LOGO)}" styleClass="logo"/>
<h:panelGrid width="92%" columns="3" columnClasses="headerCol2,headerCol3,headerCol4">
<h:outputText styleClass="titel"
value="#{cM.getStringProp('de.gai_netconsult.kodaba.text.title')}"/>
<span class="timer">Automatischer Logout in: </span>
<h:outputText id="counter" styleClass="timer"></h:outputText>
</h:panelGrid>
</div>
The time is placed at the id="counter" position.
This is the Javascript code: "script.js"
var hiddenField;
var timeoutInSeconds;
var originalTimeout;
var originalCounter;
var initialized = false;
function initCountdown(){
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// do stuff
startCountdown();
}
function getHiddenField() {
if (hiddenField != null) {
timeoutInSeconds = parseInt(hiddenField.value) * 60;
return timeoutInSeconds;
}
try {
hiddenField = document.getElementById('originalTimeoutId');
} catch (e) {
timeoutInSeconds = 0;
}
return timeoutInSeconds;
}
function getOriginalCounter(){
return document.getElementById('counter');
}
function resetInactivityTimer() {
if (initialized) {
console.log("resetInactivityTimer - initialized: " + initialized);
stopCountdown();
countdown(timeoutInSeconds, 'counter');
}
}
function startCountdown () {
timeoutInSeconds = getHiddenField();
if(timeoutInSeconds == 0) return;
originalCounter = getOriginalCounter();
if(timeoutInSeconds == null || originalCounter == null) {
setTimeout(function(){
startCountdown()}, 1000);
}
if(timeoutInSeconds != null && originalCounter != null){
initialized = true;
originalTimeout = timeoutInSeconds;
countdown(originalTimeout, 'counter');
}
}
function stopCountdown() {
var element = document.getElementById('counter');
clearTimeout(element.timerId);
}
function leadingzero(number) {
return (number < 10) ? '0' + number : number;
}
function countdown(seconds, target) {
var element = document.getElementById(target);
element.seconds = seconds;
calculateAndShow('counter');
}
function calculateAndShow(target) {
var element = document.getElementById('counter');
if (element.seconds >= 0) {
element.timerId = window.setTimeout(calculateAndShow,1000,target);
var h = Math.floor(element.seconds / 3600);
var m = Math.floor((element.seconds % 3600) / 60);
var s = element.seconds % 60;
element.innerHTML=
leadingzero(h) + ':' +
leadingzero(m) + ':' +
leadingzero(s);
element.seconds--;
} else {
completed(target);
return false;
}
}
function completed(target) {
var element = document.getElementById(target);
element.innerHTML = "<strong>Finished!<\/strong>";
}
Some things I tried is replacing
<script type="text/javascript">
window.onload = initCountdown();
</script>
with
<script type="text/javascript">
if (window.attachEvent) {window.attachEvent('onload', initCountdown());}
else if (window.addEventListener) {window.addEventListener('load', initCountdown(), false);}
else {document.addEventListener('load', initCountdown(), false);}
</script>
This leads to a "Typeconflict".
or with:
<rich:jQuery name="jcountdown" query="initCountdown()" timing="onload"/>
None of this helps.
I was able to get my timer to work in the end and I will post my solution here:
Problem 1:
<script type="text/javascript">
jQuery(document).ready(function(){
startCountdown();
});
</script>
instead of window.onload = startCountdown(); solves the problem.
Important: when using any console.log() statements, the function will only be executed when the developer console is opened! (F12).
Problem 2: (AJAX)
Richfaces version 3.3 is simply not compatible with any Internet Explorer Version above IE8.
It is important to apply a patch. This site describes the process in detail.
I also had to make many changes to the Javascript code. I am sure this could be much more elegantly written, but I confess I don't really know much Javascript at all... I'm posting my code anyway, in case somebody may find it useful:
var hiddenField;
var timeoutInSeconds;
var originalTimeout;
var originalCounter;
function getHiddenField() {
if (hiddenField != null) {
timeoutInSeconds = parseInt(hiddenField.value) * 60 -1;
timeoutInSeconds;
return timeoutInSeconds;
}
try {
hiddenField = document.getElementById('originalTimeoutId');
} catch (e) {
timeoutInSeconds = 0;
}
return timeoutInSeconds;
}
function getOriginalCounter(){
return document.getElementById('counter');
}
function startCountdown () {
timeoutInSeconds = getHiddenField();
if(timeoutInSeconds == 0) return;
originalCounter = getOriginalCounter();
if(timeoutInSeconds == null || originalCounter == null) {
setTimeout(function(){
startCountdown()}, 1000);
}
if(timeoutInSeconds != null && originalCounter != null){
originalTimeout = timeoutInSeconds;
countdown(originalTimeout, 'counter');
}
}
function countdown(seconds, target) {
var element = document.getElementById(target);
element.seconds = seconds;
calculateAndShow('counter');
}
function resetCountdown(){
var element = document.getElementById('counter');
element.seconds = timeoutInSeconds;
updateDisplay(element);
}
function calculateAndShow() {
var element = document.getElementById('counter');
if (element.seconds > 0) {
element.timerId = window.setTimeout(calculateAndShow,1000,'counter');
updateDisplay(element);
element.seconds--;
} else {
completed();
return false;
}
}
function updateDisplay(element){
var h = Math.floor(element.seconds / 3600);
var m = Math.floor((element.seconds % 3600) / 60);
var s = element.seconds % 60;
element.innerHTML =
leadingzero(h) + ':' +
leadingzero(m) + ':' +
leadingzero(s);
}
function leadingzero(number) {
return (number < 10) ? '0' + number : number;
}
function completed() {
var element = document.getElementById('counter');
element.innerHTML = "<strong>Beendet!<\/strong>";
logoutCallBackToServer();
}
Somewhere in one of your xhtml files (template, Header, menu, whatever) you also need to add this line:
<a4j:jsFunction name="logoutCallBackToServer" immediate="true" action="#{identity.logout}" />
This will ensure that the user is actually logged out precisely when the countdown reaches zero, just in case this does not 100% match the actual session time out.

How to stop countdown after a few rounds?

var secondsP = document.getElementById('seconds');
var btn1 = document.getElementById("btnSurrender");
var clock = null;
btn1.addEventListener("click", surrender);
function timer () {
clearInterval(clock);
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
}
if (seconds === 0) {
}
}, 1000);
}
function surrender(){
clearInterval(clock);
secondsP.textContent = 0;
setTimeout(timer,2000);
}
timer();
setInterval(timer, 17000);
<html>
<head>
<style>
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<p id="seconds">15</p>
<button id= "btnSurrender">end now</button>
</body>
</html>
I need help with my little problem. I made a stopwatch which counts down 15 seconds. After this 15 seconds, it waits two seconds and starts again. You have option to stop counting when you want to, using "end now" button (then it'll start again after 2 sec). Now, my question is: how can I make a function which is going to stop whole counting after 3/4 rounds?
You restart the clock in surrender() using the call setTimeout(timer, 2000). All you need to do is add an if statement inside that function testing a variable that controls how many times you have run the timer, and then call/not call timer() accordingly. Here is a working example of it: https://jsfiddle.net/L38q6k5d/, but just to give you an idea of how it would work:
At the top of the js file:
var timesRun = 0
var timerInterval = null;
Inside the surrender function:
timesRun += 1 // Increment it each time the timer ends
if (timesRun > 4) { // If the timer has run less than 4 times
return; // this will stop the function here, so we dont start the timer again
}
setTimeout(timer, 2000); // Reset the timer
Inside the timer function,
if (timesRun > 1) {
clearInterval(timerInterval);
return; // end the function here
}
When starting the initial timer:
timer();
timerInterval = setInterval(timer, 17000);
Complete JS:
var secondsP = document.getElementById('seconds');
var btn1 = document.getElementById("btnSurrender");
var clock = null;
var timerInterval = null;
// New Code
var numberOfTimesRun = 0; // this is where we keep track of how many times the timer has run
btn1.addEventListener("click", surrender);
function timer () {
clearInterval(clock);
// New Code
if (numberOfTimesRun > 1) {
clearInterval(timerInterval);
return; // end the function here
}
// End New Code
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
numberOfTimesRun += 1; // so we know that 1 iteration of the timer has been completed
}
if (seconds === 0) {
}
}, 1000);
}
function surrender(){
clearInterval(clock);
secondsP.textContent = 0;
//New Code
numberOfTimesRun += 1;
if (numberOfTimesRun > 4) {
return; // end the function there
}
setTimeout(timer, 2000)
//End New Code
}
timer();
timerInterval = setInterval(timer, 17000);

Re-starting a timer after stopping it

Problem: When I click my start button after stopping my timer, I can't seem to get the timer to resume.
Desired result: For any given timer, when I click the start button, after clicking the stop button, I want the time to resume where it left off.
I figured that when clicking the start button, it would just call the setInterval function again after being cleared, however, I am having issues figuring that out.
I have the stop event in each function in the same scope as the intervalID var's, which hold the setInterval functions itself. Which is why the stop button works. Calling the timer functions(setPomodoro, setLongBreak, setShortBreak) resets their timer's to the original state. I can't seem to grasp how to resume from the timer's time when it's stopped.
JSBIN: http://jsbin.com/bucalequsi/edit?html,js,output
Re-creation:
// Problem: Pomodor timer does not have functionality
// Solution: Add functionality to the pomodor timer.
// IF a break timer is running WHILE another is clicked, stop running timer, start clicked timer.
// Reset current interval time on reset button.
// If break buttons are clicked more than once, reset the time.
window.onload = function() {
var pomodoro = document.querySelector('#set-time'),
longBreak = document.querySelector('#long-brk'),
shortBreak = document.querySelector('#short-brk'),
stopButton = document.querySelector('#stop'),
startButton = document.querySelector('#start'),
resetButton = document.querySelector('#reset'),
container = document.querySelector('#container'),
actionButtons = document.querySelector('#buttons'),
timer = document.querySelector('#timer');
// Click event for break timers.
container.addEventListener('click', function(e) {
// store event target
var el = e.target;
if (el === pomodoro) {
setPomodoro();
} else if (el === longBreak) {
setLongBreak();
} else if (el === shortBreak) {
setShortBreak();
}
e.stopPropagation();
}, false);
// 1.1a Create a timer that counts down from 25 minutes.
function setPomodoro() {
var mins = 24;
var secs = 60;
var intervalID = setInterval(function() { //set unique interval ID for each SI func.
timer.innerHTML = mins + ':' + secs;
secs--;
if (secs === 0) {
mins--;
secs = 60;
}
}, 1000);
// 2.2 When stop button is clicked, timer stops
stopButton.addEventListener('click', function() {
clearInterval(intervalID);
}, false);
}
// 1.2a Create a timer that counts down from 10 minutes
function setLongBreak() {
var mins2 = 9;
var secs2 = 60;
var intervalID2 = setInterval(function() {
timer.innerHTML = mins2 + ':' + secs2;
secs2--;
if (secs2 === 0) {
mins2--;
secs2 = 60;
}
}, 1000);
stopButton.addEventListener('click', function(){
clearInterval(intervalID2);
}, false);
}
// 1.3a Create a timer that counts down from 5 minutes.
function setShortBreak() {
var mins3 = 4;
var secs3 = 60;
var intervalID3 = setInterval(function() {
timer.innerHTML = mins3 + ':' + secs3;
secs3--;
if (secs3 === 0) {
mins3--;
secs3 = 60;
}
}, 1000);
stopButton.addEventListener('click', function() {
clearInterval(intervalID3);
}, false);
}
};
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Pomodoro Timer</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="normalize.css">
<link rel="stylesheet" href="main.css">
</head>
<body>
<div id="container">
<header>
<div id="header"><h1>Pomodoro Timer</h1></div>
</header>
<div class="row">
<ul id="breaks">
<li><input type="submit" value="Pomodoro" id="set-time"></li>
<li><input type="submit" value="Long Break" id="long-brk"></li>
<li><input type="submit" value="Short Break" id="short-brk"></li>
</ul>
</div>
<h1 id=timer></h1>
<div class="row">
<ul id="buttons">
<li><input type="submit" value="Start" id="start"></li>
<li><input type="submit" value="Stop" id="stop"></li>
<li><input type="submit" value="Reset" id="reset"></li>
</ul>
</div>
<footer>
<p>© Laere 2016</p>
</footer>
</div>
<script src="script.js"></script>
</body>
</html>
When the set... functions are started with the buttons, you always initialise the times to starting values. Instead, if there is a timer already running you have to parse the paused time string into minutes and seconds and use those values to set your vars mins and secs.
Maybe something like this will work?
function setPomodoro() {
if(timer.innerHTML.length > 0){
var t = timer.innerHTML.split(':');
var mins = parseInt(t[0]);
var secs = parseInt(t[1]);
}
else{
var mins = 24;
var secs = 60;
}
var intervalID = setInterval(function() { //set unique interval ID for each SI func.
timer.innerHTML = mins + ':' + secs;
secs--;
if (secs === 0) {
mins--;
secs = 60;
}
}, 1000);
// 2.2 When stop button is clicked, timer stops
stopButton.addEventListener('click', function() {
clearInterval(intervalID);
}, false);
}

Pause / Resume jQuery Countdown Timer

I'm trying to make a countdown timer that can be paused with a single HTML5 button tag using a JS onClick() event, or more preferably, using jQuery with something like $("#pause_resume").off('click').on('click', firstClick)in conjunction with another function. Logically, I would assume the task would require getting the current values of both $.min and $.sec and then setting these values, while switching functions, until the "resume" button is pressed again. But I honestly have no idea how to go about doing this. I've looked at other code on this site and others, but what I saw was heavily deprecated and not in line with my project plan. Any insight is appreciated.
HTML:
<p class="timer">
<span class="min"></span>:<span class="sec"></span>/
<span class="fullTime">1:30</span>
</p>
JavaScript:
<script type="text/javascript">
var timer = $('.timer');
var leadingZero = function(n) {
if (n < 10 && n >= 0)
return '0' + n;
else
return n;
};
var minutes = 1;
var seconds = 30;
setInterval(function () {
var m = $('.min', timer),
s = $('.sec', timer);
if (seconds == 0) {
minutes--;
seconds = 59;
} else {
seconds--;
}
m.text(minutes);
s.text(leadingZero(seconds));
}, 1000);
</script>
Well, I think this is what you want. http://jsfiddle.net/joey6978/67sR2/3/
I added a button that toggles a boolean on click to determine whether to set your function in the interval or to clear the interval.
var clicked=true;
var counter;
$('button').click(function(){
if(clicked){
counter=setInterval(function () {
var m = $('.min', timer),
s = $('.sec', timer);
if (seconds === 0) {
minutes--;
seconds = 59;
} else {
seconds--;
}
m.text(minutes);
s.text(leadingZero(seconds));
}, 1000);
}
else{
clearInterval(counter);
}
clicked=!clicked;
});

Categories