my couter time gets reset on page load - javascript

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.

Related

How can I make a timer subtract five minutes when a buton is pressed?

I'm making a riddle where people have 45 minutes to find the solution, but I want the timer to go down five minutes when they answer incorrectly to prevent them from just guessing the answer. This is what I have for the timer:
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
var cat1 = $("input[#name=Verdachte]:checked");
if (cat1.val() != "2") {
cat1.val("you are right :)");
cat1.attr("disabled", true);
start -= 1000 * 60 * 5;
}
if (diff <= 0) {
start = Date.now() + 1000;
}
};
timer();
setInterval(timer, 1000);
}
window.onload = function() {
var fortyfiveMinutes = 60 * 45,
display = document.querySelector('#time');
startTimer(fortyfiveMinutes, display);
}
But it just keeps subtracting five minutes all the time, so I made a send button for it:
$("#results").click(function() {
if (cat1.val() === "2") {
cat1.val("you are right :)");
cat1.attr("disabled", true);
start -= 1000 * 60 * 5;
}
};
But now the timer just disappears completely, how can I fix this?
try this , I create a new function to check value and set varaibles as globals to access easy ,and change value of 'start' if value of textbox is wrong
var start = Date.now();
function startTimer(duration, display) {
var diff,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
start = Date.now() + 1000;
}
};
timer();
setInterval(timer, 1000);
}
window.onload = function() {
var fortyfiveMinutes = 60 * 45,
display = document.querySelector('#time');
startTimer(fortyfiveMinutes, display);
}
function checkValue() {
var cat1 = $("#Verdachte");
if (cat1.val() == "2" || cat1.attr("disabled")) {
cat1.val("you are right :)");
cat1.attr("disabled", true);
} else {
cat1.val("Wrong :(");
start -= 1000 * 60 * 5;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time"></div>
<input id="Verdachte">
<button onclick="checkValue()"> click me</button>

Date difference in PHP

I'm trying to get a countdown system on my site that countdown only 24hrs from the time of registration.
The idea is after registration, a subscriber has 24hrs to make payment after which he will be blocked. I have the registration time already in my database but i'm stuck with the countdown. I've tried several help online but I don't seem to be getting it right.
The javascript is set to work with the seconds remaining for the user to make payment var count = '86400'; but i want to use php to calculate from the time registered till the current time how long he has left to register, so that when i refresh the page, it doesn't start from the current time left. So i did this var count = <?php echo strtotime($row_rsPH['date'])-time(); ?>;
<script type="text/javascript">
var count = <?php echo strtotime($row_rsPH['date'])-time(); ?>;
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + ":" + minutes + ":" + seconds; // watch for spelling
}
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
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;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = 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);
}
</script>
<p>Time Left to make payment: <span id='timer'></span></p>
I used a countdown sample here http://www.hashemian.com/tools/javascript-countdown.htm and under TargetDate i used this php code
<?php
$date = date_create($row_rsPH['date']);
date_add($date, date_interval_create_from_date_string('1 days'));
echo date_format($date, 'Y-m-d h:i A');
?>
Hope this helps someone else

jQuery time clock counter

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.

How do you decrement time for minutes seconds hundredths?

Suppose you wanted to set a timer to whatever time you want will be displayed in the form 00:00:00 minutes, seconds, and hundredths. How would you go about doing so? Please any help is greatly appreciated.
Here is the link in JSFiddle:
https://jsfiddle.net/mxpuejvz/2/
function decrement(){
var time = 600;
var mins = parseInt((time / 100) / 60);
var secs = parseInt((time / 100) % 60);
var hundredths = parseInt(time % 100);
if(mins < 10) {
mins = "0" + mins;
}
if(secs < 10) {
secs = "0" + secs;
}
if(hundredths < 10) {
hundredths = "0" + hundredths;
}
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + hundredths;
if (hundredths === 0){
if(time ===0){
clearInterval(countdownTimer);
document.getElementById("output").innerHTML = "Time's Up.";
}else{
time--;
}
var countdownTimer = setInterval('decrement()', 10)
}
}
}
Three issues appear to need attention.
"time to go" needs to be stored outside the screen update function and decremented or calculated each time the screen is updated.
using parseInt to convert numbers to integer numbers is regarded as a hack by some. Math.floor() or integer calculation can be alternatives.
Timer call backs are not guaranteed to made exactly on time: counting the number of call backs for a 10msec time does not give the number of 1/100ths of elapsed time.
The following code is an example of how it could work, minus any pause button action.
var countdownTimer;
var endTime;
var counter = 0; // ** see reply item 3. **
function startCountDown( csecs) // hundredths of a second
{ endTime = Date.now() + 10*csecs; // endTime in millisecs
decrement();
countdownTimer = setInterval(decrement, 10);
counter = 0; // testing
}
function decrement()
{ var now, time, mins, secs, csecs, timeStr;
++ counter; // testing
now = Date.now();
if( now >= endTime)
{ time = 0;
timeStr = "Times up! counter = " + counter;
clearInterval( countdownTimer);
}
else
{ time = Math.floor( (endTime - now)/10); // unit = 1/100 sec
csecs = time%100;
time = (time-csecs)/100; // unit = 1 sec
secs = time % 60;
mins = (time-secs)/60; // unit = 60 secs
timeStr =
( (mins < 10) ? "0" + mins : mins) + ":" +
( (secs < 10) ? "0" + secs : secs) + ":" +
( (csecs < 10) ? "0" + csecs : csecs);
}
document.getElementById("output").innerHTML=timeStr;
}
The argument to startCountDown gives the number of 1/100ths of second for the count down. If the counter result is the same as the argument,try swapping browser tabs and back again during the countdown.
HTML to test:
<button type="button" onclick="startCountDown(600)">start</button>
<div id="output">
</div>

Getting 2 errors with a JavaScript Countdown Timer

I have created a countdown timer which counts down to 5pm every day then resets to 5pm the following day.
The timer works perfectly, but I am getting 2 errors from the code which I am Struggling to solve.
The code is below:
function startTimer(display) {
var date = new Date();
var h17 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 17);
if(date.getHours() >= 17) {
h17.setDate(h17.getDate()+1);
}
h17 = h17.getTime();
var diff,
hours,
minutes,
seconds;
function timer() {
diff = (((h17 - Date.now()) / 1000) | 0);
// Setting and displaying hours, minutes, seconds
hours = (diff / 3600) | 0;
minutes = ((diff % 3600) / 60) | 0;
seconds = (diff % 60) | 0;
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = hours + ":" + minutes + ":" + seconds;
};
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var display = document.querySelector('#time');
startTimer(display);
};
The errors are looking like line 14: diff = (((h17 - Date.now()) / 1000) | 0);
Returning the message : "Object doesn't support this property or method: line 14"
and line 25: display.textContent = hours + ":" + minutes + ":" + seconds;
Returning the message "Cannot set property 'textContent' of null".
Turns out the issue was coming from binding the output to the #time ID in the html.
Since I had put the script in the and only used this on certain pages, the error was coming from the pages where there was no <div id="time">, so the display was null.
I have fixed this by checking if the element ID exists before running the script.
if(document.getElementById("time")){
var display = document.querySelector('#time');
startTimer(display);
} else {
}

Categories

Resources