Javascript seconds countdown - javascript

I have been trying for hours to make a javascript function that will take an input time in seconds and provide a countdown. For some reason it just refuses to count down after the first second and I can't figure out why not.
Here is my HTML:
<span style="display:none;" id="unixtime_coming_0">600</span><span onload='timer()' id="timer_coming_0"></span>
And here is my javascript:
setInterval(function timer() {
var count = document.getElementById("unixtime_coming_0").innerHTML;
count = count - 1;
if (count <= 0) {
clearInterval(counter);
return;
}
var days = Math.floor(count / 86400);
var hours = Math.floor(count / 3600) % 24;
var minutes = Math.floor(count / 60) % 60;
var seconds = count % 60;
document.getElementById("timer_coming_0").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s"; // watch for spelling
}, 1000);

Defining a named function doesn't return anything. You have to define it outside of setInterval:
var counter = setInterval(timer, 1000);
function timer() {
var unixtime = document.getElementById("unixtime_coming_0");
var count = parseInt(unixtime.innerHTML, 10);
unixtime.innerHTML = count - 1;
if (count < 1) {
clearInterval(counter);
return;
}
var days = Math.floor(count / 86400);
var hours = Math.floor(count / 3600) % 24;
var minutes = Math.floor(count / 60) % 60;
var seconds = count % 60;
document.getElementById("timer_coming_0").innerHTML= days + "d " + hours + "h " + minutes + "m " + seconds + "s"; // watch for spelling
}
I'd get rid of the setInterval completely. Just call timer via setTimeout inside of timer itself.

count is being reset to 600 on every loop. Just move its declaration outside of the function, like so:
var count = parseInt(document.getElementById("unixtime_coming_0").innerHTML, 10);
setInterval(function timer() {
count = count - 1;
[...]

For accurate count down you need to use new Date().getTime(). Please have a look at this answer for a similar question https://stackoverflow.com/a/15635372/1523245

Related

Clear the label before calling a JavaScript function which displays timer through the same function [Session Timeout]

I tried to display timer on webpage in label (label id is MsgTimer) using following function. But when the function is called the 2/more times then 2/ more timers are displayed and it won't reset the timer but overload the label text and display multiple timers on a lable. I want to reset the label text each time the function is called.
function startTimer() {
var x;
clearInterval(x);
document.getElementById("MsgTimer").innerHTML = "";
// Here I was supposed to fetch the SessionTimeout data from appsettings.json
// But for now I entered data manually for 15 minutes
var countDownDate = new Date().getTime() + 900000;
// Update the count down every 1 second
x = setInterval(function () {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor(distance / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// add a zero in front of numbers<10
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
hours = checkTime(hours);
minutes = checkTime(minutes);
seconds = checkTime(seconds);
// Display the result in the element with id="lblTime"
document.getElementById("MsgTimer").innerHTML = "";
document.getElementById("MsgTimer").innerHTML = "Session Expires In" + " " + minutes + " : " + seconds + "";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("MsgTimer").innerHTML = "SESSION EXPIRED";
window.alert("Session Timeout");
}
}, 1000);
}
startTimer();
The problem with your code might be the var x; declaration, because variables declared using var keywords, are actually function scoped.
So, every time startTimer(); is called it is creating a new x variable within the function scope only and because of that the clearInterval(x) cannot clear the previous interval because it cannot access the previous value of x from previous startTimer(); call.
Try moving your var x; declaration outside the function and see if it works.
Updated [Working]:
/* Timer - Display Session Timeout */
var x = 0;
function startTimer() {
var countDownDate = (new Date().getTime()) + ((parseInt(#SessionTimer)) * 60000);
clearInterval(x);
x = setInterval(function () {
var now = new Date().getTime();
var distance = countDownDate - now;
var hours = Math.floor(distance / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
hours = checkTime(hours);
minutes = checkTime(minutes);
seconds = checkTime(seconds);
document.getElementById("MsgTimer").innerHTML = "Session Expires In" + " " + hours + " : " + minutes + " : " + seconds + "";
if (distance < 0) {
clearInterval(x);
document.getElementById("MsgTimer").innerHTML = "SESSION EXPIRED";
window.alert("Session Timeout");
}
}, 1000);
}
startTimer();
Alternative [JQuery]:
/* Show 15 Minutes Timer */
var timer2 = "15: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('Session Expires In' + ' ' + minutes + ':' + seconds);
timer2 = minutes + ':' + seconds;
}, 1000);

Persistance countdown on refresh

I have one problem to solve and i am not a master in javascript, basically when is loaded my element id which will be in my code down to start a count down from 2hours minutes and seconds but i have links where on click refresh the page and is refreshing my counter i found full counter here is link:
JavaScript count down, add hours & minutes
var count = 7200;
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
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 + " ora " + minutes + " minute" + seconds + " secunde ramase ";
}
I just want to make this counter to not reset on refresh.
Use localStorage:
var count = parseInt(localStorage.getItem("count")) || 7200;
function timer() {
//...
document.getElementById("timer").innerHTML = hours + " ora " + minutes + " minute" + seconds + " secunde ramase ";
localStorage.setItem("count", count);
}
To redirect your page and clear localStorage when the timer hits 0, add this code to your function:
function timer() {
count = count - 1;
if (count == 0) {
localStorage.removeItem("count");
window.location.href = "home.html";
}
//...
}

wants javascript countdown to continue from where it was even after refresh

I am designing a javaScript countdown for 3 hours using the below code
<div id="timer"></div>
<script type="text/javascript">
var count = 10800;
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
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 + "hours " + minutes + "minutes and " + seconds + " seconds left to complete this transaction"; // watch for spelling
}
</script>
but the only issue I am having here is whenever I refresh the page the countdown starts all over again. I want it to resume from where it stopped.
You need to store the data into some persistent storage method, such as cookies, the browsers localStorage, or write data out to an external data source (such as a database through an API). Otherwise the session data is lost between browser refreshes.
For example, if you wanted to use localStorage:
<script type="text/javascript">
// properties
var count = 0;
var counter = null;
window.onload = function() {
initCounter();
};
function initCounter() {
// get count from localStorage, or set to initial value of 1000
count = getLocalStorage('count') || 1000;
counter = setInterval(timer, 1000); //1000 will run it every 1 second
}
function setLocalStorage(key, val) {
if (window.localStorage) {
window.localStorage.setItem(key, val);
}
return val;
}
function getLocalStorage(key) {
return window.localStorage ? window.localStorage.getItem(key) : '';
}
function timer() {
count = setLocalStorage('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 + "hours " + minutes + "minutes and " + seconds + " seconds left to complete this transaction"; // watch for spelling
}
</script>
<div id="timer"></div>
You can try it out here: https://jsfiddle.net/rcg4mt9x/

Timer how to fix

I was just wondering with this, how can I get it to display only seconds when minutes hit zero?
So instead of displaying "0 minutes and 41 seconds"
I would like it to only display "41 seconds"
Is this possible?
<script type="text/javascript">
var count = <? = $time['timefromdb'] ?>;
var now = Math.floor(new Date().getTime() / 1000);
count = count - now;
var counter = setInterval(timer, 1000); //1000 will* run it every 1 second
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);
var days = Math.floor(hours / 24);
minutes %= 60;
hours %= 24;
document.getElementById("clock").innerHTML = minutes + " minutes and " + seconds + " seconds";
}
</script>
Simplest would be
document.getElementById("clock").innerHTML = (minutes?minutes+ " minutes and ":"")+ seconds + " seconds";
Try this
<script type="text/javascript">
var count = <?= $time['timefromdb'] ?>;
var now = Math.floor(new Date().getTime() / 1000);
count = count - now;
var counter = setInterval(timer, 1000); //1000 will* run it every 1 second
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);
var days = Math.floor(hours / 24);
minutes %= 60;
hours %= 24;
if (minutes > 0) {
min = minutes + " minutes and ";
}
else {
min = "";
}
document.getElementById("clock").innerHTML = min + seconds + " seconds";
}
</script>

Backcountdown Timer creation in the alertbox

I have an requirement to create a timer in that will show up in the alertbox of javascript and it will start counting back from 4 minutes to 0.. The moment time is over , it should stop the timer. Everything I want this to be created in Javascript. I have tried with following code that I got from this link:
Timer in Javascript
But it is not working with me. I have done this::
<script>
window.onload = CreateTimer("timer", 30);
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function Tick() {
if (TotalSeconds <= 0) {
alert("Time's up!")
return;
}
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function UpdateTimer() {
var Seconds = TotalSeconds;
var Days = Math.floor(Seconds / 86400);
Seconds -= Days * 86400;
var Hours = Math.floor(Seconds / 3600);
Seconds -= Hours * (3600);
var Minutes = Math.floor(Seconds / 60);
Seconds -= Minutes * (60);
var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
Timer.innerHTML = TimeStr;
}
function LeadingZero(Time) {
return (Time < 10) ? "0" + Time : +Time;
}
</script>
<div class="page">
<div id='timer' style="float: left; width: 50%; background-color: red; color: white;"></div>
</div>
I hope, it will help you.
window.onload = CreateTimer("timer", 30);
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer()
window.setTimeout(Tick, 1000); // remove double quote
}
function Tick() {
if (TotalSeconds <= 0) {
alert("Time's up!")
return;
}
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout(Tick, 1000); // remove double quote
}
function UpdateTimer() {
var Seconds = TotalSeconds;
var Days = Math.floor(Seconds / 86400);
Seconds -= Days * 86400;
var Hours = Math.floor(Seconds / 3600);
Seconds -= Hours * (3600);
var Minutes = Math.floor(Seconds / 60);
Seconds -= Minutes * (60);
var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
Timer.innerHTML = TimeStr;
}
function LeadingZero(Time) {
return (Time < 10) ? "0" + Time : +Time;
}
Comments are there where I had done changes. Also you need to modify your code as per requirement as alert message is display after every moment when seconds equal to 0 whether time is remaining. I didn't know your requirement about this I didn't touch that code.
Please follow this link for live demo.

Categories

Resources