jQuery time clock counter - javascript

I'm trying to make a simple jQuery Time counter just to count the user working time in my application displaying hours and minutes
HTML:
<body>
<div><input type="text" class="time"/></div>
</body>
JS:
function startTimer(duration) {
var timer = duration,hours, minutes;
setInterval(function () {
hours = parseInt(timer / 3600, 10)
minutes = parseInt(timer / 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
$('input[type=text].time').val(hours + ":" + minutes);
if (++timer < 0) {
timer = 0;
}
}, 1);
}
jQuery(function ($) {
var minutes = 0
startTimer(minutes);
});
Fiddle:
http://jsfiddle.net/df773p9m/1856/
The problem is that at this time the counter does not reset when reach 60 minutes and continues to count, although the hours were updated.
Notes: I've set the interval to 1 ms in order to test the operation.

you should use % after the division, otherwise it'll continue
check this updated jsfiddle
EDIT
Sean is right, I have fixed the code, the 24 should be in the % not the division also note that I'm multiplying duration by 60 to get the mins from the seconds
no need for the reset mins line anymore
function startTimer(duration) {
var timer = duration*60,hours, minutes;
setInterval(function () {
hours = parseInt((timer / 3600)%24, 10)
minutes = parseInt((timer / 60)%60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
$('input[type=text].time').val(hours + ":" + minutes);
if (++timer < 0) {
timer = 0;
}
}, 1);
}
jQuery(function ($) {
var minutes = 1339;
startTimer(minutes);
});

http://jsfiddle.net/df773p9m/1859/
If your timer is in minutes, and it's counting up one minute at a time, you want to divide the total time by 60 to get hours. Then you can get the remainder with the modulo operator % for the remaining minutes:
function startTimer(duration, display) {
var timer = duration,
hours,
minutes;
setInterval(function () {
hours = parseInt(timer / 60, 10);
minutes = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
$('#time').val(hours + ":" + minutes);
// I have no idea what you're trying to do here, it appears this will never evaluate to true:
if (++timer < 0) {
timer = duration;
}
}, 100); // this number should be changed to 60000 for it to be one minute (60,000 milliseconds = 1 minute)
}
jQuery(function ($) {
var minutes = 0,
display;
startTimer(minutes, display);
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder_()
Remainder (%)
The remainder operator returns the remainder left over when one
operand is divided by a second operand. It always takes the sign of
the dividend, not the divisor. It uses a built-in modulo function to
produce the result, which is the integer remainder of dividing var1 by
var2 — for example — var1 modulo var2. There is a proposal to get an
actual modulo operator in a future version of ECMAScript, the
difference being that the modulo operator result would take the sign
of the divisor, not the dividend.

Related

JavaScript Stopwatch - Trouble Displaying a Leading Digit

I've been trying to create a simple stopwatch script using JavaScript in order to display the number of seconds, minutes, and hours that have elapsed.
Ideally, I'd like to have the time displayed as follows:
hh:mm:ss
With JavaScript, I was unable to find a built-in way to format numbers such that they contain a leading zero if a number is only one digit in length. This is where my problem lies - the logic that I added to the script to add a leading "0" works for the seconds display, but not for the minutes or hours displays.
Instead of only adding a leading "0" and then the one-digit value, the code I wrote will add in a "0" for each iteration of the setInterval() function, creating a long string of "0"s and then the current minutes or hours values.
I'm having trouble understanding why that is happening for the minutes and hours sections, but not for the seconds section when the code being used is the same.
In theory, I know that I'm essentially just adding another "0" to a string that then gets displayed each time the setInterval() function executes, but I can't seem to figure out why that doesn't happen in the seconds section. And what's also interesting is that the leading "0"s don't start getting added until the timer reaches two seconds.
Please see below for the code that I wrote for this stopwatch script. I'd certainly appreciate any insight that anyone could provide to get this working as expected.
let seconds = 0;
let minutes = 0;
let hours = 0;
function stopWatch(){
//Increment seconds on each "tick" of the stopwatch
seconds++;
//Check if minutes or hours needs to be incremented (which should happen every 60 seconds or 60 minutes, resepctively)
if(seconds / 60 == 0){
seconds = 0;
minutes++;
if(minutes / 60 == 0){
minutes = 0;
hours++;
}
}
//If the number of elapsed seconds, minutes, or hours is less than 10, add a 0 to the front of the number.
if(seconds < 10){
seconds = "0" + seconds;
}
if(minutes < 10){
minutes = "0" + minutes;
}
if(hours < 10){
hours = "0" + hours;
}
//Print the results to the "display" div in the HTML
document.getElementById("display").innerHTML = hours + ":" + minutes + ":" + seconds;
}
//Run the stopWatch() function every 1000ms
window.setInterval(stopWatch, 1000);
<div id="display">00:00:00</div>
And for what it's worth, I kept the <script></script> tags in the HTML document for simplicity, but once I get it working, I'll likely move the script to its own script.js file and potentially add in some buttons to start, stop, and reset the stopwatch.
let seconds = 0;
let minutes = 0;
let hours = 0;
let seconds_string = "0";
let minutes_string = "0";
let hours_string = "0";
function stopWatch(){
//Increment seconds on each "tick" of the stopwatch
seconds++;
//Check if minutes or hours needs to be incremented (which should happen every 60 seconds or 60 minutes, resepctively)
if(seconds / 60 === 1){
seconds = 0;
minutes++;
if(minutes / 60 === 1){
minutes = 0;
hours++;
}
}
//If the number of elapsed seconds, minutes, or hours is less than 10, add a 0 to the front of the number.
if(seconds < 10){
seconds_string = "0" + seconds.toString();
} else {
seconds_string = seconds.toString();
}
if(minutes < 10){
minutes_string = "0" + minutes.toString();
} else {
minutes_string = minutes.toString();
}
if(hours < 10){
hours_string = "0" + hours.toString();
} else {
hours_string = hours.toString();
}
//Print the results to the "display" div in the HTML
document.getElementById("display").innerHTML = hours_string + ":" + minutes_string + ":" + seconds_string;
}
//Run the stopWatch() function every 1000ms
window.setInterval(stopWatch, 1000);
<div id="display">00:00:00</div>
When you do "0" + minutes (and seconds, and hours) those variables get automatically converted into a string, consisting of two characters, a zero and something else.
Since the variables carry through each iteration, the next time you are adding another "0" character to the beginning of the string, and so-on.
The reason it's not happening to seconds is because you are converting seconds BACK to an int at the beginning of the loop when you do seconds++. So it becomes a string, then an int, then a string, etc.
To see this in action, try this snippet:
var test = 1;
console.log( typeof test ); //outputs "number"
test = "0" + test;
console.log( typeof test ); //outputs "string"
test++;
console.log( typeof test); //outputs number
My suggestion would be to separate counting units from display units. See if minutes is less than 10, and if so set outputMinutes to "0" + minutes. Do the same for seconds and hours. Then you just change the outputMinutes, outputSeconds, and outputHours each time, while the actual minutes, seconds, and hours variables remain as integers.
Instead of test in the if if the value is less than 10, test the length of that value as a string, if it is less than 2 (which means any number less than 10 in this case), then you add another "0" as a string to the value;
Like below:
let seconds = 0;
let minutes = 0;
let hours = 0;
function stopWatch(){
seconds++;
if(seconds / 60 == 0){
seconds = 0;
minutes++;
if(minutes / 60 == 0){
minutes = 0;
hours++;
}
}
if(seconds.toString().length < 2){
seconds = "0" + seconds;
}
if(minutes.toString().length < 2){
minutes = "0" + minutes;
}
if(hours.toString().length < 2){
hours = "0" + hours;
}
document.getElementById("display").innerHTML = hours + ":" + minutes + ":" + seconds;
}
window.setInterval(stopWatch, 1000);
<div id="display">00:00:00</div>

my couter time gets reset on page load

recently i implemented a count timer for my shopping website that sets a limit of 24 hours when they create an order and not check out with a payment,so that counter reminds him/her that have to make a payment. The timer that is in our table is the start time and is adjusted by the current time up to 24 hours - after that, the order is cancelled.
Now i have a problem, when i reload the page the counter restarts from 24 hours this is my code
<script type="text/javascript">
function startTimer(duration, display) {
var start = '<?php echo $pending_order_date;?>';
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
if(minutes >= 60){
hours = (minutes / 60) | 0;
minutes = (minutes % 60) | 0;
}else{
hours = 0;
}
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = hours + ":" + minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var twentyfourhour = 60 * 60 *24,
display = document.querySelector('#time');
startTimer(twentyfourhour, display);
};
</script>
Please see my code, i get the timestamp in php from my table and the count.
Your help would be appreciated.
You need to store your left off duration somewhere. localStorage seems to be better fit
function startTimer(duration, display) {
var start = '<?php echo $pending_order_date;?>';
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
if(minutes >= 60){
hours = (minutes / 60) | 0;
minutes = (minutes % 60) | 0;
}else{
hours = 0;
}
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = hours + ":" + minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
localStorage.setItem('timer', diff);
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var twentyfourhour = 60 * 60 *24,
display = document.querySelector('#time');
var timePassed = localStorage.getItem('timer');
startTimer((typeof timer!=='undefined' ? timer : twentyfourhour), display);
};
so each time your duration changes, it will update localStorage timer value. when you reload page, it will look for timer item in localStorage and will get that value, if it doesn't exist then will use 24 hrs. you may also add a controller to remove timer once it is expired, and store it with the order number or something so you can use multiple values. but this should give you an idea.

countdown timer with number reduction after set point?

I've got a working countdown timer which starts at 30 minutes.
With only 3 minutes left (so after 27 minutes) I'd like the number 250 to decrease at random intervals from 3 minutes left down to the end of the countdown.
Any ideas?
https://codepen.io/anon/pen/bWoGrb
// Stopwatch
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var thirtyMinutes = 60 * 30,
display = document.querySelector('#stopwatch');
startTimer(thirtyMinutes, display);
};
<div id='stopwatch'></div>
Maybe use something like this (I hope I clearly understood the question):
Just using a if/else within the condition something to say: Go normal when more than 60*3, and when under 60*3 seconds rest, there is chance to do nothing
// Stopwatch
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
if(timer > 60*3 || Math.random() < 0.25) {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
} else {
/* do not reduce the timer to wait 1 interval more */
/* or maybe do like `timer -= Math.random()` if you want to reduce it faster */
}
}, 1000);
}
window.onload = function () {
var thirtyMinutes = 60 * /*30*/ 4, // just set to 4 to see faster
display = document.querySelector('#stopwatch');
startTimer(thirtyMinutes, display);
};
<div id='stopwatch'></div>

Cannot replace a specific part of string

I've some problem with a string replace, in particular I've a php that return an array, each index of array contains a specific string of translation. So essentially, this array are saved inside: GlobalVariables.language['hello_world'], that for example return Hello world.
Now I've an array index that contains this translation string:
wait $seconds seconds before try again
I set the seconds inside an interval function that working as a countdown:
setInterval(function ()
{
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
text = text.replace('$seconds', seconds);
console.log(text);
$('.alert').text(text);
if (--timer < 0)
{
timer = 0; //Stoppo il timer
}
}, 1000);
this will return a string like this:
wait 20 seconds before try again
but only for the first time, 'cause later the $seconds part of the string is already replaced, I though to replace only digital number of text for second timing, but I can't do this 'cause before call setInterval I append the string to another that contains a digital number.
How can I solve this problem?
dont replace the original variable but use a different one.
text will then always contain $seconds:-
setInterval(function() {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
var text2 = text.replace('$seconds', seconds);
console.log(text2);
$('.alert').text(text2);
if (--timer < 0) {
timer = 0; //Stoppo il timer
}
}, 1000);
First time it works as $seconds is found in the string. However next time(2nd iteration onward) since $seconds not exists in the text, thus its not replaced.
You should persist original with element and used it as template.
//Perists original text with element
var alertElem = $('.alert');
alertElem.data('text', text);
setInterval(function (){
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
alertElem.text(function(){
return alertElem.data('text').replace('$seconds', seconds)
});
if (--timer < 0)
{
timer = 0;
}
}, 1000);

I need some explanation for some of this code

This a count down timer. I don't understand how var timer works. What is its set value after each interval? How does the timer produce the number of minutes and seconds? Could some one break down step-by-step how this bit of code operates?
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
Here is the complete code:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
minutes = parseInt(timer / 60, 10);
Minutes are number of current total seconds divided by 60 (seconds in a minute).
E.g.: 65 / 60 = 1 minute. We just keep the integer part.
seconds = parseInt(timer % 60, 10);
Seconds are calculated as the module 60 of the current total seconds counter.
E.g.: 65 % 60 = 5 (1 minute, 5 seconds)
[Notice that in the second line the parseInt is unnecessary.]
var timer = duration, seconds, minutes;
this can also be written as:
var timer = duration;
var seconds;
var minutes;
You can declare and instialise multiple variables at a time in javascript.
var a,
b,
c;
is same as
var a;
var b;
var c;
also you can intialize variable too so
var timer = duration, seconds, minutes;
is same as writing
var timer = duration;
var seconds;
var minutes;
(as #Lorenzo already mentioned)
var timer = duration, seconds, minutes declares 3 variables with only the first getting initialized. It is the same as writing:
var timer = duration;
var seconds;
var minutes;

Categories

Resources