How to Save and retrieve 24hrs Countdown timer to Local.Storage - javascript

I am a JS newbie. I have a 24hrs Countdown timer which resets on page reload, however i want to save the start progress using LocalStorage so that it ends exactly after 24hrs. Which means that it does not stop or restart as soon as it has started even when the page is closed. It would always continue the countdown when the page is visited. My code is below
<div class="ml-2">Time Remainingā€ƒ<span id="remainingTime"></span></div>
<script>
// this code set time to 24 hrs
var timer2 = "36:00:00";
var session_timer = localStorage.getItem('timer2');
if(session_timer){
console.log('timer2',session_timer);
timer2 = session_timer;
}
var interval = setInterval(function() {
var timer = timer2.split(':');
//by parsing integer, I avoid all extra string processing
var hours = parseInt(timer[0], 10);
var minutes = parseInt(timer[1], 10);
var seconds = parseInt(timer[2], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
hours = (minutes < 0) ? --hours : hours;
if (hours < 0) clearInterval(interval);
minutes = (minutes < 0) ? 59 : minutes;
minutes = (minutes < 10) ? '0' + minutes : minutes;
hours = (hours < 10) ? '0' + hours : hours;
if (minutes < 0) clearInterval(interval);
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
minutes = (minutes < 10) ? minutes : minutes;
timer2 = hours+ ':' +minutes + ':' + seconds;
if(hours <= 0 && minutes == 0 && seconds == 0){
// if you want to delete it on local storage
// localStorage.removeItem('timer');
console.log('Transaction Cancelled')
}
else{
$('#remainingTime').html(timer2);
// if you want to save it on local storage
// localStorage.setItem('timer', timer2);
}
}, 1000);
</script>

To save something in Local Storage you can use localStorage.setItem(key, value)
To get something from Local Storage you can use localStorage.getItem(key, value)
if(hours <= 0 && minutes == 0 && seconds == 0){
// if you want to delete it on local storage
localStorage.removeItem('timer');
console.log('Transaction Cancelled')
}
else{
$('#remainingTime').html(timer2);
// if you want to save it on local storage
localStorage.setItem('timer', timer2.toString());
}

Using luxon js and calculating as Millis versus handling hours, minutes and seconds
// this code set time to 24 hrs
let duration = luxon.Duration.fromObject({
days: 1
});
var interval;
function tick() {
let remaining = localStorage.getItem("interval") || duration.toMillis();
remaining -= 1000;
let d = luxon.Duration.fromMillis(remaining);
console.log(d.toHuman());
localStorage.setItem("interval", remaining);
}
function onLoad() {
var interval = setInterval(tick, 1000);
console.log("Timer Started");
}
function onUnLoad() {
cancelInterval(interval);
console.log("Timer Stopped");
}
onLoad();
onUnLoad();
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>

Related

Clearing/Resetting Bound Timer/Countdown Event On Click

I've a script like this:
<span class="countdown">5:00</span>
<script type="text/javascript">
$(document).ready(function() {
var timer2 = "5:01";
var interval = setInterval(function() {
var timer = timer2.split(':');
//by parsing integer, I avoid all extra string processing
var minutes = parseInt(timer[0], 10);
var seconds = parseInt(timer[1], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) clearInterval(interval);
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
//minutes = (minutes < 10) ? minutes : minutes;
$('.countdown').html(minutes + ':' + seconds);
timer2 = minutes + ':' + seconds;
}, 1000);
});
</script>
On the same page, I have a button which is supposed to reset the timer as part of it's functionality.
$('#liveorderfeedwidget').on('click', function() {
$(".countdown").empty();
$('.countdown').off();
var timer2 = "5:01";
var interval = setInterval(function() {
var timer = timer2.split(':');
//by parsing integer, I avoid all extra string processing
var minutes = parseInt(timer[0], 10);
var seconds = parseInt(timer[1], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) clearInterval(interval);
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
//minutes = (minutes < 10) ? minutes : minutes;
$('.countdown').html(minutes + ':' + seconds);
timer2 = minutes + ':' + seconds;
}, 1000);
. . . . . . . .
But whenever I click the button to reset the timer, it does not fully clear the first binded event.
Let's say I click the button when it is at 2:39.
The timer/countdown class span flashes, says 5:00, and then goes in continuous cycle like this
2:39 5:00 2:38 4:59 2:37 4:58 etc etc
Apparently $(".countdown").empty(); and $('.countdown').off(); in my reset button timer is not working as intended.
What is needed to fully clear the previous event and refresh the .countdown to its fully reset state?
edit:
Here's a full jsfiddle with the issue observed:
https://jsfiddle.net/fw6Lzm0o/
You have 2 variables named interval. One is global and one is local to button onclick. Then you are missing the clearInterval() method that actually stops the timer. Then the empty or off is not required, you want to put 5:00 there.
Here is the code that needs to be changed:
$('#liveorderfeedwidget').on('click', function() {
$(".countdown").html('5:00');
//$(".countdown").empty();
//$('.countdown').off();
var timer2 = "5:01";
clearInterval(interval); //clear the timer
interval = setInterval(function() {
var timer = timer2.split(':');
//by parsing integer, I avoid all extra string processing
var minutes = parseInt(timer[0], 10);
var seconds = parseInt(timer[1], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) clearInterval(interval);
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
//minutes = (minutes < 10) ? minutes : minutes;
$('.countdown').html(minutes + ':' + seconds);
timer2 = minutes + ':' + seconds;
}, 1000);
});
Here is the working fiddle.
Even better would be to make a function and call it on page load and on click... rather than having 2 set of exact duplicate codes.
like this:
var timer2, interval;
startTimer();
$('#liveorderfeedwidget').on('click', function() {
clearInterval(interval);
startTimer();
});
function startTimer() {
timer2 = "5:01";
$(".countdown").html('5:00');
interval = setInterval(function() {
var timer = timer2.split(':');
//by parsing integer, I avoid all extra string processing
var minutes = parseInt(timer[0], 10);
var seconds = parseInt(timer[1], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) clearInterval(interval);
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
// minutes = (minutes < 10) ? minutes : minutes;
$('.countdown').html(minutes + ':' + seconds);
timer2 = minutes + ':' + seconds;
}, 1000);
}
Here is the working fiddle for this.

Stop timer after disconnect call in twilio php

I am working with call connect and disconnect module in php using twilio api,Whenever i disconnect then timer not stop, Here is my code
//timer start when click on answer button
$('#answer').on('click', function() {
var countdown = document.getElementsByTagName('countdown')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 0,
t;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
countdown.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
document.getElementById('checkyear').value = countdown.textContent;
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
timer();
});
//Timer should stop when disconnect the call
Twilio.Device.disconnect(function (conn) {
clearTimeout(t);
});
Twilio developer evangelist here.
I think the issue here is one of scope. Your variable t, which is set to the ID of the timeouts you are using to count time up, is only available within the event handling function that is called when you click on the answer button.
When it's inside the Twilio.Device.disconnect handler, t is undefined.
I would rearrange your code so that the timing variables and functions are outside of the click event handler, so they are in scope for the disconnect handler. Something like this:
var t, seconds, minutes, hours;
Twilio.Device.disconnect(function(conn) {
clearTimeout(t);
});
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
countdown.textContent =
(hours ? (hours > 9 ? hours : '0' + hours) : '00') +
':' +
(minutes ? (minutes > 9 ? minutes : '0' + minutes) : '00') +
':' +
(seconds > 9 ? seconds : '0' + seconds);
document.getElementById('checkyear').value = countdown.textContent;
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
$('#answer').on('click', function() {
var countdown = document.getElementsByTagName('countdown')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear');
seconds = 0;
minutes = 0;
hours = 0;
timer();
});

Stopwatch in Javascript is slower than normal time

I want to make a stopwatch in JavaScript that could count milliseconds, seconds and minutes. This is what I have: (you can stop the timer by pressing space)
var counter = document.getElementsByTagName('h1')[0];
var miliseconds = 0;
var seconds = 0;
var minutes = 0;
function Add() {
miliseconds++;
if (miliseconds >= 99) {
miliseconds = 0;
seconds++;
if (seconds >= 59) {
seconds = 0;
minutes++;
}
}
counter.textContent = (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" +
(seconds ? (seconds > 9 ? seconds : "0" + seconds) : "00") + ":" +
(miliseconds ? (miliseconds > 9 ? miliseconds : "0" + miliseconds) : "00");
Timer();
}
function Timer() {
t = setTimeout(Add, 10);
}
Timer();
document.addEventListener("keypress", function(e) {
if (e.keyCode === 32) {
clearTimeout(t);
}
});
<h1 id="counter">00:00:00</h1>
The problem is that it seems to not go at the proper speed, meaning that when I compare it to other timers, it gradually becomes slower than them (i.e the speed at which the timer is counting slows down over time). So suddenly, there are 5-second differences, then it becomes 7-second differences and so on.
Any help would be appreciated.
You should create a startTime variable, then calculate the elapsedTime, and use that to calculate additional variable to show.
var startTime = Date.now();
setTimeout(function(){
var elapsedTime = Date.now() - startTime;
// Additional code to calculate hour, minute, second, milisecond here
}, 10);

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.

Set countdown/timer to continue after reset or do not reset after refreshing the page

I'm trying to get a countdown / timer which continues after refreshing the page without restarting from beginning. I have used JavaScript but it resets when reloading the page.
var timer2 = "1:30";
$('.countdown').html(timer2);
var interval = setInterval(function() {
var timer = timer2.split(':');
//by parsing integer, I avoid all extra string processing
var minutes = parseInt(timer[0], 10);
var seconds = parseInt(timer[1], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0){
clearInterval(interval);
$('input[name=ansSubmit]').trigger("click");
}else{
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
//minutes = (minutes < 10) ? minutes : minutes;
$('.countdown').html(minutes + ':' + seconds);
timer2 = minutes + ':' + seconds;
}
}, 1000);
The timer continues until the user clicks on submit, but is it possible to resume it automatically with PHP or JavaScript if user reloads the page?
Just use the browser Window.localStorage (or sessionStorage if it fits better).
<div class="countdown"></div>
<button style="display:none">FINISH!!!</button>
<script>
$(document).ready(function() {
var timer2 = localStorage.getItem('timer');
if(timer2 === null) timer2 = "1:30";
$('.countdown').html(timer2);
var interval = setInterval(function() {
var timer = timer2.split(':');
var minutes = parseInt(timer[0], 10);
var seconds = parseInt(timer[1], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0){
clearInterval(interval);
localStorage.removeItem('timer');
$('button').show();
}else{
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
$('.countdown').html(minutes + ':' + seconds);
timer2 = minutes + ':' + seconds;
localStorage.setItem('timer',timer2);
}
}, 1000);
});
</script>
The only way I can think of setting the $_SESSION variable of time left, would be to use an ajax call inside your javascript every second or so, that calls a php script with a get variable in the filepath. This php script would set a session variable, and your timer page would check if something like $_SESSION['timeLeft'] was set, and echo out a js variable for timeleft, if not set echo out 0.
separate php:
<?php
if(isset($_GET['timeLeft'])){
$_SESSION['timeLeft'] = $_GET['timeLeft'];
}
?>
Inside timer JS (using JQuery):
$.ajax({url: "somePath/updateTimeLeft.php?timeLeft=1234"});
and when you load the page, in your php
if(isset($_SESSION['timeLeft'])){
echo 'var timeLeft = ' . $_SESSION['timeLeft'] . ';';
$_SESSION['timeLeft'] = undefined;
}else{
echo 'var timeLeft = 0;';
}

Categories

Resources