Clearing/Resetting Bound Timer/Countdown Event On Click - javascript

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.

Related

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

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>

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();
});

Hiding div classes when timer ends in Javascript

I have a timer script but I am having a few issues with it. Just a day ago, it was working perfectly fine, as intended. Now, the timer no longer hides the div class when it ends. Didn't change the HTML or JavaScript code at all, but for whatever reason it no longer removes the div class.
Here is the JavaScript 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) {
display.textContent = 'OFFER HAS EXPIRED.';
$('.formme').css('visibility', 'hidden');
}
console.log(parseInt(seconds));
window.localStorage.setItem('seconds', seconds);
window.localStorage.setItem('minutes', minutes);
}, 1000);
}
window.onload = function() {
sec = parseInt(window.localStorage.getItem('seconds'));
min = parseInt(window.localStorage.getItem('minutes'));
if (parseInt(sec) == 0 && parseInt(min) == 0) {
$('#time').text('OFFER HAS EXPIRED.');
$('.formme').css('visibility', 'hidden');
} else {
var start = 5 * 60;
if (sec > 0 || min > 0) {
start = parseInt(min * 60) + sec;
}
// var start = 60 * 5;
display = document.querySelector('#time');
startTimer(start, display);
}
};
On top of that, I used localStorage to prevent the timer from resetting when the webpage is refreshed. However, when the timer is finished, instead of going straight to the "OFFER HAS EXPIRED" text, it counts down from 00:01 then displays the text. Can anyone help me out? Thanks in advance!

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;';
}

Changing a span display into a readonly input

I have a timer countdown which displays in a <span>, I need it to output into a readonly <input> instead so I can calculate with the value. Is there any way to change this?
I tried
document.getElementById("timedown").value = display;
I tried various other things which just got messy and didn't work. Below is the function and the input
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;
if (diff <= 0) {
// faaopoopo se tasi sekone
start = Date.now() + 1000;
}
};
// amata vave
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 10,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
<div class="transtime">
<form>
<input type="text" id="timedown" value="0" readonly/>
</form>
</div>
Change
display.textContent = minutes + ":" + seconds;
to
document.getElementById("timedown").value = minutes + ":" + seconds;
or change
display = document.querySelector('#timedown');
and
display.value = minutes + ":" + seconds;
Here is a working codepen
Change the function to this:
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.value= minutes + ":" + seconds;
if (diff <= 0) {
// faaopoopo se tasi sekone
start = Date.now() + 1000;
}
};
changing the value instead of the text value and it should work

Categories

Resources