multiple stopwatch in jquery [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to make multiples stopwatches in jquery, but the problem is i want the stopwatch the respective stopwatch to sun when we hit the corresponding button, and should stop when we hit button for another stopwatch and that respective stopwatch should start simultaneously, please see the image for reference, i know the question is not so clear, sorry for inconvenience.
thanks in advance.

try this one:
$(document).ready(function() {
(function($){
$.extend({
APP : {
formatTimer : function(a) {
if (a < 10) {
a = '0' + a;
}
return a;
},
startTimer : function(dir) {
var a;
// save type
$.APP.dir = dir;
// get current date
$.APP.d1 = new Date();
switch($.APP.state) {
case 'pause' :
// resume timer
// get current timestamp (for calculations) and
// substract time difference between pause and now
$.APP.t1 = $.APP.d1.getTime() - $.APP.td;
break;
default :
// get current timestamp (for calculations)
$.APP.t1 = $.APP.d1.getTime();
// if countdown add ms based on seconds in textfield
if ($.APP.dir === 'cd') {
$.APP.t1 += parseInt($('#cd_seconds').val())*1000;
}
break;
}
// reset state
$.APP.state = 'alive';
$('#' + $.APP.dir + '_status').html('Running');
// start loop
$.APP.loopTimer();
},
pauseTimer : function() {
// save timestamp of pause
$.APP.dp = new Date();
$.APP.tp = $.APP.dp.getTime();
// save elapsed time (until pause)
$.APP.td = $.APP.tp - $.APP.t1;
// change button value
$('#' + $.APP.dir + '_start').val('Resume');
// set state
$.APP.state = 'pause';
$('#' + $.APP.dir + '_status').html('Paused');
},
stopTimer : function() {
// change button value
$('#' + $.APP.dir + '_start').val('Restart');
// set state
$.APP.state = 'stop';
$('#' + $.APP.dir + '_status').html('Stopped');
},
resetTimer : function() {
// reset display
$('#' + $.APP.dir + '_ms,#' + $.APP.dir + '_s,#' + $.APP.dir + '_m,#' + $.APP.dir + '_h').html('00');
// change button value
$('#' + $.APP.dir + '_start').val('Start');
// set state
$.APP.state = 'reset';
$('#' + $.APP.dir + '_status').html('Reset & Idle again');
},
endTimer : function(callback) {
// change button value
$('#' + $.APP.dir + '_start').val('Restart');
// set state
$.APP.state = 'end';
// invoke callback
if (typeof callback === 'function') {
callback();
}
},
loopTimer : function() {
var td;
var d2,t2;
var ms = 0;
var s = 0;
var m = 0;
var h = 0;
if ($.APP.state === 'alive') {
// get current date and convert it into
// timestamp for calculations
d2 = new Date();
t2 = d2.getTime();
// calculate time difference between
// initial and current timestamp
if ($.APP.dir === 'sw') {
td = t2 - $.APP.t1;
// reversed if countdown
} else {
td = $.APP.t1 - t2;
if (td <= 0) {
// if time difference is 0 end countdown
$.APP.endTimer(function(){
$.APP.resetTimer();
$('#' + $.APP.dir + '_status').html('Ended & Reset');
});
}
}
// calculate milliseconds
ms = td%1000;
if (ms < 1) {
ms = 0;
} else {
// calculate seconds
s = (td-ms)/1000;
if (s < 1) {
s = 0;
} else {
// calculate minutes
var m = (s-(s%60))/60;
if (m < 1) {
m = 0;
} else {
// calculate hours
var h = (m-(m%60))/60;
if (h < 1) {
h = 0;
}
}
}
}
// substract elapsed minutes & hours
ms = Math.round(ms/100);
s = s-(m*60);
m = m-(h*60);
// update display
$('#' + $.APP.dir + '_ms').html($.APP.formatTimer(ms));
$('#' + $.APP.dir + '_s').html($.APP.formatTimer(s));
$('#' + $.APP.dir + '_m').html($.APP.formatTimer(m));
$('#' + $.APP.dir + '_h').html($.APP.formatTimer(h));
// loop
$.APP.t = setTimeout($.APP.loopTimer,1);
} else {
// kill loop
clearTimeout($.APP.t);
return true;
}
}
}
});
$('#sw_start').live('click', function() {
$.APP.startTimer('sw');
});
$('#cd_start').live('click', function() {
$.APP.startTimer('cd');
});
$('#sw_stop,#cd_stop').live('click', function() {
$.APP.stopTimer();
});
$('#sw_reset,#cd_reset').live('click', function() {
$.APP.resetTimer();
});
$('#sw_pause,#cd_pause').live('click', function() {
$.APP.pauseTimer();
});
})(jQuery);
});
DEMO HERE
OR
$(function () {
// Never assume one widget is just used once in the page. You might
// think of adding a second one. So, we adjust accordingly.
$('.stopwatch').each(function () {
// Cache very important elements, especially the ones used always
var element = $(this);
var running = element.data('autostart');
var hoursElement = element.find('.hours');
var minutesElement = element.find('.minutes');
var secondsElement = element.find('.seconds');
var millisecondsElement = element.find('.milliseconds');
var toggleElement = element.find('.toggle');
var resetElement = element.find('.reset');
var pauseText = toggleElement.data('pausetext');
var resumeText = toggleElement.data('resumetext');
var startText = toggleElement.text();
// And it's better to keep the state of time in variables
// than parsing them from the html.
var hours, minutes, seconds, milliseconds, timer;
function prependZero(time, length) {
// Quick way to turn number to string is to prepend it with a string
// Also, a quick way to turn floats to integers is to complement with 0
time = '' + (time | 0);
// And strings have length too. Prepend 0 until right.
while (time.length < length) time = '0' + time;
return time;
}
function setStopwatch(hours, minutes, seconds, milliseconds) {
// Using text(). html() will construct HTML when it finds one, overhead.
hoursElement.text(prependZero(hours, 2));
minutesElement.text(prependZero(minutes, 2));
secondsElement.text(prependZero(seconds, 2));
millisecondsElement.text(prependZero(milliseconds, 3));
}
// Update time in stopwatch periodically - every 25ms
function runTimer() {
// Using ES5 Date.now() to get current timestamp
var startTime = Date.now();
var prevHours = hours;
var prevMinutes = minutes;
var prevSeconds = seconds;
var prevMilliseconds = milliseconds;
timer = setInterval(function () {
var timeElapsed = Date.now() - startTime;
hours = (timeElapsed / 3600000) + prevHours;
minutes = ((timeElapsed / 60000) + prevMinutes) % 60;
seconds = ((timeElapsed / 1000) + prevSeconds) % 60;
milliseconds = (timeElapsed + prevMilliseconds) % 1000;
setStopwatch(hours, minutes, seconds, milliseconds);
}, 25);
}
// Split out timer functions into functions.
// Easier to read and write down responsibilities
function run() {
running = true;
runTimer();
toggleElement.text(pauseText);
}
function pause() {
running = false;
clearTimeout(timer);
toggleElement.text(resumeText);
}
function reset() {
running = false;
pause();
hours = minutes = seconds = milliseconds = 0;
setStopwatch(hours, minutes, seconds, milliseconds);
toggleElement.text(startText);
}
// And button handlers merely call out the responsibilities
toggleElement.on('click', function () {
(running) ? pause() : run();
});
resetElement.on('click', function () {
reset();
});
// Another advantageous thing about factoring out functions is that
// They are reusable, callable elsewhere.
reset();
if(running) run();
});
});
DEMO HERE

Related

How do I get my timer to stop, when my 10th and last question has been answered?

The goal I am trying to achieve is to get my timer to stop when all the questions of my quiz has been answered. I have 10 total questions. I have been able to get the timer to start. But getting ot to stop on the click of submit on the 10th question is something I can't figure out.
Let me know if you know what I am doing
StackOverflow said my code was too long... I added my code to codepen. I also included my JS on here.
// variables
var score = 0; //set score to 0
var total = 10; //total nmumber of questions
var point = 1; //points per correct answer
var highest = total * point;
//init
console.log('script js loaded')
function init() {
//set correct answers
sessionStorage.setItem('a1', "b");
sessionStorage.setItem('a2', "a");
sessionStorage.setItem('a3', "c");
sessionStorage.setItem('a4', "d");
sessionStorage.setItem('a5', "b");
sessionStorage.setItem('a6', "d");
sessionStorage.setItem('a7', "b");
sessionStorage.setItem('a8', "b");
sessionStorage.setItem('a9', "d");
sessionStorage.setItem('a10', "d");
}
// timer
// var i = 1;
// $("#startButton").click(function (e) {
// setInterval(function () {
// $("#stopWatch").html(i);
// i++;
// }, 1000);
// });
// $("#resetButton").click(function (e) {
// i = 0;
// });
//hide all questions to start
$(document).ready(function() {
$('.questionForm').hide();
//show question 1
$('#question1').show();
$('.questionForm #submit').click(function() {
//get data attribute
current = $(this).parents('form:first').data('question');
next = $(this).parents('form:first').data('question') + 1;
//hide all questions
$('.questionForm').hide();
//show next question in a cool way
$('#question' + next + '').fadeIn(400);
process('' + current + '');
return false;
});
});
//process answer function
function process(n) {
// get input value
var submitted = $('input[name=question' + n + ']:checked').val();
if (submitted == sessionStorage.getItem('a' + n + '')) {
score++;
}
if (n == total) {
$('#results').html('<h3>Your score is: ' + score + ' out of ' + highest + '!</h3> <button onclick="myScore()">Add Your Name To Scoreboard!</a>')
}
return false;
}
window.yourPoints = function() {
return n;
}
function myScore() {
var person = prompt("Please enter your name", "My First Name");
if (person != null) {
document.getElementById("myScore").innerHTML =
person + " " + score
}
}
// function showTime() {
// var d = new Date();
// document.getElementById("clock").innerHTML = d.toLocaleTimeString();
// }
// setInterval(showTime, 1000);
var x;
var startstop = 0;
window.onload = function startStop() { /* Toggle StartStop */
startstop = startstop + 1;
if (startstop === 1) {
start();
document.getElementById("start").innerHTML = "Stop";
} else if (startstop === 2) {
document.getElementById("start").innerHTML = "Start";
startstop = 0;
stop();
}
}
function start() {
x = setInterval(timer, 10);
} /* Start */
function stop() {
clearInterval(x);
} /* Stop */
var milisec = 0;
var sec = 0; /* holds incrementing value */
var min = 0;
var hour = 0;
/* Contains and outputs returned value of function checkTime */
var miliSecOut = 0;
var secOut = 0;
var minOut = 0;
var hourOut = 0;
/* Output variable End */
function timer() {
/* Main Timer */
miliSecOut = checkTime(milisec);
secOut = checkTime(sec);
minOut = checkTime(min);
hourOut = checkTime(hour);
milisec = ++milisec;
if (milisec === 100) {
milisec = 0;
sec = ++sec;
}
if (sec == 60) {
min = ++min;
sec = 0;
}
if (min == 60) {
min = 0;
hour = ++hour;
}
document.getElementById("milisec").innerHTML = miliSecOut;
document.getElementById("sec").innerHTML = secOut;
document.getElementById("min").innerHTML = minOut;
document.getElementById("hour").innerHTML = hourOut;
}
/* Adds 0 when value is <10 */
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function reset() {
/*Reset*/
milisec = 0;
sec = 0;
min = 0
hour = 0;
document.getElementById("milisec").innerHTML = "00";
document.getElementById("sec").innerHTML = "00";
document.getElementById("min").innerHTML = "00";
document.getElementById("hour").innerHTML = "00";
}
//adding an event listener
window.addEventListener('load', init, false);
https://codepen.io/rob-connolly/pen/xyJgwx
Any help would be appreciated.
its a pretty simple solution just call the stop function in the if condition of n == total
if (n == total) {
$('#results').html('<h3>Your score is: ' + score + ' out of ' + highest + '!</h3>
<button onclick="myScore()">Add Your Name To Scoreboard!</a>')
stop()
}
https://codepen.io/nony14/pen/VwYREgr
Try using clearInterval() to stop the timer.
https://codepen.io/thingevery/pen/dyPrgwz

How to clear JS timers

I've got a user which i get from database. For each user is possible to reset his password. But it's possible only one time for three minutes. If password was reseted less than three minutes, I show timer with JS, which show how much time left for next reset and reset button is disabled. When countdown is finished, button become availiable and displayed inscription "Password reset avaliable". Because the each user has his own timer, when I select another user, previous timer must be stopped with reset() function, and must be started other timer. It's just the only one timer must be in one time.
Timer:
var timerCount = 0;
function startTimer(minute, second) {
timerCount++;
start(minute, second);
}
function start(minute, second) {
disableButton('resetPasswordButton');
var m = minute;
var s = second;
if (timerCount == 0) {
document.getElementById('expiredTimeOutputText').innerHTML = "Password reset avaliable";
m = 0;
s = 0;
enableButton('resetPasswordButton');
return ;
}
if (s == 0) {
if (m == 0) {
reset();
document.getElementById('expiredTimeOutputText').innerHTML = "Password reset avaliable!";
enableButton('resetPasswordButton');
return ;
}
m--;
s = 59;
} else
s--;
document.getElementById('expiredTimeOutputText').innerHTML = m + ":" + s;
setTimeout(function () {
start(m, s);
}, 1000);
}
function reset() {
if (timerCount > 0) {
timerCount = 0;
}
}
function enableButton(id){
document.getElementById(id).disabled = false;
}
function disableButton(id){
document.getElementById(id).disabled = true;
}
method to start timer on button click
public void changePassword() {
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.execute("startTimer(\"0\", \"40\")");
Date tmpDate = new Date();
Long diff = tmpDate.getTime();
mainDataBean.setResetTimer(applicantsTableSelectedRow.get("ID"), diff.toString());
}
method to start timer on user change
public void checkTimerForNewUser() {
RequestContext requestContext = RequestContext.getCurrentInstance();
Date tmpDate = new Date();
Long currentTime = tmpDate.getTime();
requestContext.execute("reset()");
if (applicantsTableSelectedRow != null) {
if (!mainDataBean.getResetTimer(applicantsTableSelectedRow.get("ID")).equals("noTimer")) {
Long applicantTimerTime = Long.parseLong(mainDataBean.getResetTimer(applicantsTableSelectedRow.get("ID")));
if (currentTime - applicantTimerTime > timerValue) {
mainDataBean.deleteResetTimer(applicantsTableSelectedRow.get("ID"));
}
else {
expiredTimeMinute = (timerValue - (currentTime - applicantTimerTime)) / 60000;
expiredTimeSecond = (timerValue - (currentTime - applicantTimerTime)) / 1000 - expiredTimeMinute * 60;
requestContext.execute("startTimer(\"" + expiredTimeMinute + "\", \"" + expiredTimeSecond + "\")");
}
}
}
}
If consistently reset user password, one after another, everything works fine. But if I consistently reset password for 5 users, and after that I return to first user with reseted password, if time isn't expired, I've got all 5 timers, which overlap one another, display 5 different times 5 time in second. But in theory they must stop because of reset function. How does it possible to make the only one timer exist? Do I stop functions wrong?
Example with clearTimeout:
function start(minute, second) {
disableButton('resetPasswordButton');
var m = minute;
var s = second;
if (timerCount == 0) {
document.getElementById('expiredTimeOutputText').innerHTML = "Reset Button Available!";
clearTimeout(timeout);
enableButton('resetPasswordButton');
return ;
}
if (s == 0) {
if (m == 0) {
reset();
clearTimeout(timeout);
document.getElementById('expiredTimeOutputText').innerHTML = "Reset Button Available!";
enableButton('resetPasswordButton');
return ;
}
m--;
s = 59;
} else
s--;
document.getElementById('expiredTimeOutputText').innerHTML = m + ":" + s;
timeout = setTimeout(function () {
start(m, s);
}, 1000);
}
You can clear timers with:
clearTimeout for setTimeout
clearInterval for setInterval
Example:
// will *never* run since we clear it below, immediately after we
// create it.
var timeout = setTimeout(() => {
console.log('foo')
}, 1000)
clearTimeout(timeout)
// will run only *once* since we clear it when it's called
var interval = setInterval(() => {
console.log('bar')
clearInterval(interval)
}, 1000)

Using setInterval in a loop to change interval

I am using the technique in the second answer here:
Changing the interval of SetInterval while it's running
but the change in the interval is not being set. Code is also using OpenLayers 3:
var coordinate,
i = 1,
length = multipointCoords[0].length;
var currentTime = tracksTime[0];
var nextTime = tracksTime[1];
speedOption = 100; // the highter this value, the faster the tracks, see next line
var transitionTime = (nextTime - currentTime) / speedOption;
var timer;
timer = setInterval(function() {
segmentConstruction(multipointCoords, tracksTime);
}, transitionTime);
function segmentConstruction(multipointCoords, tracksTime) {
coordinate = ol.proj.fromLonLat(multipointCoords[0][i]);
lineString.appendCoordinate(coordinate);
if (i === length - 1) {
clearInterval(timer);
} else {
i++;
map.addLayer(trackLayer);
clearInterval(timer);
currentTime = tracksTime[i];
nextTime = tracksTime[i + 1];
timer = setInterval(function() {
segmentConstruction(multipointCoords);
}, transitionTime);
};
};
What am I doing wrong?
Thanks.
var currentTime = tracksTime[0];
var nextTime = tracksTime[1];
speedOption = 100; // the highter this value, the faster the tracks, see next line
var transitionTime = (nextTime - currentTime) / speedOption;
You calculate transitionTime here.
if (i === length - 1) {
clearInterval(timer);
} else {
i++;
map.addLayer(trackLayer);
clearInterval(timer);
currentTime = tracksTime[i];//<------------------|
nextTime = tracksTime[i + 1];//<-----------------|
timer = setInterval(function() {// |
segmentConstruction(multipointCoords);// |
}, transitionTime);// <----------------------------->Not redefined
};
Here you use the same transitionTime as above it is not redifined !
Why not, It's not an error, but ...
I don't think your issue come from the timer, but from the param's you have.
Here a snippet to see that your code concerning timing and interval have no problem :
I just removed everything not concerned by 'timing' and interval.
var log = function(val){
console.log(val);
document.getElementById('el').innerHTML+='<div><pre>' + val + '</pre><div>';
}
var timer ,
i = 1 ,
length = 5 ,
transitionTime = 200 ;
timer = setInterval(function() {
log('first timerId : ' + timer);
segmentConstruction()
}, transitionTime );
function segmentConstruction(multipointCoords, tracksTime) {
log(' \tsegmentConstruction : i = ' + i + ' / ' + length);
//if (i === length - 1) {
if (i >= length - 1) {
clearInterval(timer);
log('\t\twe finish with : i = ' + i + ' / ' + length);
} else {
i++;
clearInterval(timer);
timer = setInterval(function() {
log('loop timerId : ' + timer);
segmentConstruction();
}, transitionTime);
};
};
<div id='el'></div>

How do I prevent loss of older objects, after I create a new one?

Il try to explain this as simple as I can.
I'm trying to make a timer app for practice. User should be abble to add a new Object, wich will be a timer + stop/start buttons.
At this point, its working with one object, but when I create another object, the old one stops working(i belive it loses the pointer to it, or somthing like that), and the new one works.
Dont worry, about the buttons functionality,thats not important, all I want to understand how do I save the object, after a new one is created.
here is JS:
var startTime = 0;
var itemNum = 0;
var obName;
var arrayForTimers = [];
function timerObject(obName) {
this.nameField = "start";
this.classField = "timer";
this.block = " ";
this.obName = obName;
this.startButton = " ";
this.stopButton = " ";
this.placeholder = document.getElementsByClassName("timer-placeholder")[0];
this.addBlock = function () {
this.block = document.createElement("DIV");
this.block.className = this.classField;
this.block.className += " " + this.obName;
this.placeholder.appendChild(this.block);
}
this.renderTime = function () {
this.startTime = startTime;
this.endTime = new Date();
// time difference in ms
this.timeDiff = this.endTime - this.startTime;
// strip the miliseconds
this.timeDiff /= 1000;
// get seconds
this.seconds = Math.round(this.timeDiff % 60);
// remove seconds from the date
this.timeDiff = Math.floor(this.timeDiff / 60);
// get minutes
this.minutes = Math.round(this.timeDiff % 60);
// remove minutes from the date
this.timeDiff = Math.floor(this.timeDiff / 60);
// get hours
this.hours = Math.round(this.timeDiff % 24);
this.block.innerHTML = this.hours + " h " + this.minutes + " min " + this.seconds + " sec";
// window.setInterval('this.obName.renderTime()',1000);// Uncomment if you want to test your PCs limit
}
this.renderButtons = function () {
var timePassed;
//this.parentTimer = document.getElementsByClassName("timer "+this.obName)[0];
this.startButton = document.createElement("INPUT");
this.startButton.setAttribute("type", "button");
this.startButton.setAttribute("value", "start");
this.startButton.className = "start " + this.obName;
this.stopButton = document.createElement("INPUT");
this.stopButton.setAttribute("type", "button");
this.stopButton.setAttribute("value", "stop");
this.stopButton.className = "stop " + this.obName;
this.placeholder.insertBefore(this.startButton, this.block);
this.placeholder.insertBefore(this.stopButton, this.block);
this.startButton.addEventListener("click", function () {
//if (this.hours === 0 && this.minutes === 0 && this.seconds === 0){
this.startTime = new Date();
// }
tm = window.setInterval('obName.renderTime()', 1000);
})
this.stopButton.addEventListener("click", function () {
window.clearInterval(tm);
//timePassed = this.endTime - this.startTime;
//endTime = new Date();
// timePassed = endTime - startTime;
})
//give listener to clear and start interval
}
};
function createNewTimer() {
obName = document.getElementById("ObName").value;
if (obName !== "") {
obName = new timerObject(obName);
obName.addBlock();
obName.renderButtons();
startTime = new Date();
obName.renderTime();
//arrayForTimers.push(obName);
//window.setInterval('obName.renderTime()',1000);
} else {
document.getElementById("ObName").value = "Fill me";
}
};
Here is a Js Fiddle http://jsfiddle.net/3qxoea52/4/
P.S. sorry for my grammar, not my native languege.
Thanks.
The problem is here
tm = window.setInterval('obName.renderTime()', 1000);
This means that when you click any of the start buttons it will always start the object currently associated with obName.
Also, you only have a single global variable tm to store the timer, so when you do
window.clearInterval(tm);
It is clearing whichever timer was last set.
And you also have a single global startTime, which is causing all of the timers to reset whenever you create a new timer.
Another problem is that you have nothing to store the time when you stop each timer, so if you stop then restart it, it will not continue at the same point.
You can fix these problems by:
using self = this to create a stable reference to the object
use function.bind to make sure an event handler will be bound to the right timer object
add a property this.startDiff so that the time is saved when you stop then restart the clock
make tm a local variable within the TimerObject
set this.startTime within the object instead of outside it.
-- as in the code below (jsfiddle)
function TimerObject(obName) {
var self = this,
tm;
this.startTime = new Date();
this.startDiff = 0;
this.nameField = "start";
this.classField = "timer";
this.block = " ";
this.obName = obName;
this.startButton = " ";
this.stopButton = " ";
this.placeholder = document.getElementsByClassName("timer-placeholder")[0];
this.addBlock = function () {
this.block = document.createElement("DIV");
this.block.className = this.classField;
this.block.className += " " + this.obName;
this.placeholder.appendChild(this.block);
};
this.renderTime = function () {
var timeDiff = new Date() - this.startTime + this.startDiff;
this.timeDiff = timeDiff;
timeDiff /= 1000;
// get seconds
this.seconds = Math.round(timeDiff % 60);
// remove seconds from the date
timeDiff = Math.floor(timeDiff / 60);
// get minutes
this.minutes = Math.round(timeDiff % 60);
// remove minutes from the date
timeDiff = Math.floor(timeDiff / 60);
// get hours
this.hours = Math.round(timeDiff % 24);
this.block.innerHTML = this.hours + " h " + this.minutes + " min " + this.seconds + " sec";
// window.setInterval('this.obName.renderTime()',1000);// Uncomment if you want to test your PCs limit
};
this.renderButtons = function () {
var timePassed;
//this.parentTimer = document.getElementsByClassName("timer "+this.obName)[0];
this.startButton = document.createElement("INPUT");
this.startButton.setAttribute("type", "button");
this.startButton.setAttribute("value", "start");
this.startButton.className = "start " + this.obName;
this.stopButton = document.createElement("INPUT");
this.stopButton.setAttribute("type", "button");
this.stopButton.setAttribute("value", "stop");
this.stopButton.className = "stop " + this.obName;
this.placeholder.insertBefore(this.startButton, this.block);
this.placeholder.insertBefore(this.stopButton, this.block);
this.startButton.addEventListener("click", function () {
//if (this.hours === 0 && this.minutes === 0 && this.seconds === 0){
self.startTime = new Date();
// }
tm = window.setInterval(self.renderTime.bind(self), 1000);
});
this.stopButton.addEventListener("click", function () {
window.clearInterval(tm);
self.startDiff = self.timeDiff;
console.log(':', self, self.startDiff);
//timePassed = this.endTime - this.startTime;
//endTime = new Date();
// timePassed = endTime - startTime;
});
//give listener to clear and start interval
};
}
function createNewTimer() {
obName = document.getElementById("ObName").value;
if (obName !== "") {
obName = new TimerObject(obName);
obName.addBlock();
obName.renderButtons();
obName.renderTime();
//window.setInterval('obName.renderTime()',1000);
} else {
document.getElementById("ObName").value = "Fill me";
}
}
There were several issues with the code:
1. Some functions weren't being bound to the correct context (this).
2. The reference set to "obName" was global and constantly changing to the newly created instance.
3. The start time variable was global and constantly being reset every time you called the renderTime function.
I have made the modifications to your code in jsFiddle and they can be found in this update: http://jsfiddle.net/3qxoea52/5/
Rendering:
this.renderTime = function (startTime) {
if( startTime ) {
this.startTime = startTime;
}
this.endTime = new Date();
// time difference in ms
this.timeDiff = this.endTime - this.startTime;
// strip the miliseconds
this.timeDiff /= 1000;
// get seconds
this.seconds = Math.round(this.timeDiff % 60);
// remove seconds from the date
this.timeDiff = Math.floor(this.timeDiff / 60);
// get minutes
this.minutes = Math.round(this.timeDiff % 60);
// remove minutes from the date
this.timeDiff = Math.floor(this.timeDiff / 60);
// get hours
this.hours = Math.round(this.timeDiff % 24);
this.block.innerHTML = this.hours + " h " + this.minutes + " min " + this.seconds + " sec";
// window.setInterval('this.obName.renderTime()',1000);// Uncomment if you want to test your PCs limit
}
Binding:
this.startButton.addEventListener("click", function () {
//if (this.hours === 0 && this.minutes === 0 && this.seconds === 0){
this.startTime = new Date();
// }
this.tm = window.setInterval(this.renderTime.bind(this), 1000);
}.bind(this))
this.stopButton.addEventListener("click", function () {
window.clearInterval(this.tm);
//timePassed = this.endTime - this.startTime;
//endTime = new Date();
// timePassed = endTime - startTime;
}.bind(this))
CreateTimer:
function createNewTimer() {
obName = document.getElementById("ObName").value;
if (obName !== "") {
obName = new timerObject(obName);
obName.addBlock();
obName.renderButtons();
startTime = new Date();
obName.renderTime(startTime);
//window.setInterval('obName.renderTime()',1000);
} else {
document.getElementById("ObName").value = "Fill me";
}
};

How to active functionality of time in every tile and continue timer after browser is closed?

I want to display timer using html multiple div.I am able to load timer for first div,but I want my timer on only that div I clicked.For the first div,its working fine,but other div is not able to start timer.Timer also stop when browser is refreshed or closed.I want to continue timer when browser is refreshed or closed by other's.I am giving my code below :
(function($){
var row =document.getElementById('row').value;
//alert("I am testing"+row);
$.extend({
APP : {
formatTimer : function(a) {
if (a < 10) {
a = '0' + a;
}
return a;
},
startTimer : function(dir) {
var a;
// save type
$.APP.dir = dir;
// get current date
$.APP.d1 = new Date();
switch($.APP.state) {
case 'pause' :
// resume timer
// get current timestamp (for calculations) and
// substract time difference between pause and now
$.APP.t1 = $.APP.d1.getTime() - $.APP.td;
break;
default :
// get current timestamp (for calculations)
$.APP.t1 = $.APP.d1.getTime();
// if countdown add ms based on seconds in textfield
if ($.APP.dir === 'cd') {
$.APP.t1 += parseInt($('#cd_seconds').val())*1000;
}
break;
}
// reset state
$.APP.state = 'alive';
$('#' + $.APP.dir + '_status').html('Running');
// start loop
$.APP.loopTimer();
},
pauseTimer : function()
{
// save timestamp of pause
$.APP.dp = new Date();
$.APP.tp = $.APP.dp.getTime();
// save elapsed time (until pause)
$.APP.td = $.APP.tp - $.APP.t1;
// change button value
$('#' + $.APP.dir + '_start').val('Resume');
// set state
$.APP.state = 'pause';
$('#' + $.APP.dir + '_status').html('Paused');
},
stopTimer : function() {
// change button value
$('#' + $.APP.dir + '_start').val('Restart');
// set state
$.APP.state = 'stop';
$('#' + $.APP.dir + '_status').html('Stopped');
},
resetTimer : function()
{
// reset display
$('#' + $.APP.dir + '_ms,#' + $.APP.dir + '_s,#' + $.APP.dir + '_m,#' + $.APP.dir + '_h').html('00');
// change button value
$('#' + $.APP.dir + '_start').val('Start');
// set state
$.APP.state = 'reset';
$('#' + $.APP.dir + '_status').html('Reset & Idle again');
},
endTimer : function(callback)
{
// change button value
$('#' + $.APP.dir + '_start').val('Restart');
// set state
$.APP.state = 'end';
// invoke callback
if (typeof callback === 'function')
{
callback();
}
},
loopTimer : function() {
var td;
var d2,t2;
var ms = 0;
var s = 0;
var m = 0;
var h = 0;
if ($.APP.state === 'alive') {
// get current date and convert it into
// timestamp for calculations
d2 = new Date();
t2 = d2.getTime();
// calculate time difference between
// initial and current timestamp
if ($.APP.dir === 'sw') {
td = t2 - $.APP.t1;
// reversed if countdown
} else {
td = $.APP.t1 - t2;
if (td <= 0) {
//if time difference is 0 end countdown
$.APP.endTimer(function(){
$.APP.resetTimer();
$('#' + $.APP.dir + '_status').html('Ended & Reset');
});
}
}
// calculate milliseconds
ms = td%1000;
if (ms < 1) {
ms = 0;
} else {
// calculate seconds
s = (td-ms)/1000;
if (s < 1) {
s = 0;
} else {
// calculate minutes
var m = (s-(s%60))/60;
if (m < 1) {
m = 0;
} else {
// calculate hours
var h = (m-(m%60))/60;
if (h < 1) {
h = 0;
}
}
}
}
// substract elapsed minutes & hours
ms = Math.round(ms/100);
s = s-(m*60);
m = m-(h*60);
// update display
//alert("I am testing"+row);
$('#' + $.APP.dir + '_ms').html($.APP.formatTimer(ms));
$('#' + $.APP.dir + '_s').html($.APP.formatTimer(s));
$('#' + $.APP.dir + '_m').html($.APP.formatTimer(m));
$('#' + $.APP.dir + '_h').html($.APP.formatTimer(h));
// loop
$.APP.t = setTimeout($.APP.loopTimer,1);
} else {
// kill loop
clearTimeout($.APP.t);
return true;
}
}
}
});
$('#sw_start').live('click', function() {
$.APP.startTimer('sw');
});
My html code for is given below :
<li id='sw_start'>
<div>
<span id="sw_h">00</span>:
<span id="sw_m">00</span>:
<span id="sw_s">00</span>:
<span id="sw_ms">00</span>
</div>
</li>
<li id='sw_start'>
<div>
<span id="sw_h">00</span>:
<span id="sw_m">00</span>:
<span id="sw_s">00</span>:
<span id="sw_ms">00</span>
</div>
</li>

Categories

Resources