Javascript Countdown timer using SQL variable - javascript

I am new to javascript/jquery. I found the following example on the internet and I am trying to get it working with my SQL variable. But I am stuck because all it does is count down from 60 over and over again..
What I am trying to accomplish is the following. I have a variable which says how many seconds a user needs to wait before it can perform the action again $secs. What I need is to have the time and process-bar countdown with the seconds from the variable to zero. After that I will add a page reload line to it. But first the timer needs to work. I would really appreciate any help as I can not find any workable solution/explanation for my problem.
<div id='timer'></div>
<div id='progress' style='background:red; height:5px;'></div>
<script>
function started(duration) {
var TotalSeconds = "<?php echo $secs; ?>";
var documentWidth = $(document).width();
var start = Date.now();
var intervalSetted = null;
function timer() {
var diff = duration - (((Date.now() - start) / 1000) | 0);
var seconds = (diff % 60) | 0;
seconds = seconds < 10 ? "0" + seconds : seconds;
$('#timer').html("00:" + seconds);
var progresBarWidth = (seconds * documentWidth / TotalSeconds);
$('#progress').css({
width: progresBarWidth + 'px'
});
if (diff <= 0) {
clearInterval(intervalSetted);
}
}
timer();
intervalSetted = setInterval(timer, 1000);
}
started("<?php echo $secs; ?>");
</script>

You need to convert duration to time format.
<div id='timer'></div>
<div id='progress' style='background:red; height:5px;'></div>
<script>
function started(duration) {
var TotalSeconds = duration;
var documentWidth = $(document).width();
var start = Date.now();
var intervalSetted = null;
function timer() {
var diff = duration - (((Date.now() - start) / 1000) | 0);
var seconds = (diff % duration) | 0;
seconds = seconds < 10 ? "0" + seconds : seconds;
var date = new Date(0);
date.setSeconds(seconds);
var timeString = date.toISOString().substr(11, 8);
$('#timer').html(timeString);
var progresBarWidth = (seconds * documentWidth / TotalSeconds);
$('#progress').css({
width: progresBarWidth + 'px'
});
if (diff <= 0) {
clearInterval(intervalSetted);
}
}
timer();
intervalSetted = setInterval(timer, 1000);
}
started("<?php echo $secs; ?>");
</script>
function started(duration) {
var TotalSeconds = duration;
var documentWidth = $(document).width();
var start = Date.now();
var intervalSetted = null;
function timer() {
var diff = duration - (((Date.now() - start) / 1000) | 0);
var seconds = (diff % duration) | 0;
seconds = seconds < 10 ? "0" + seconds : seconds;
var date = new Date(0);
date.setSeconds(seconds);
var timeString = date.toISOString().substr(11, 8);
$('#timer').html(timeString);
var progresBarWidth = (seconds * documentWidth / TotalSeconds);
$('#progress').css({
width: progresBarWidth + 'px'
});
if (diff <= 0) {
clearInterval(intervalSetted);
}
}
timer();
intervalSetted = setInterval(timer, 1000);
}
started(60);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='timer'></div>
<div id='progress' style='background:red; height:5px;'></div>

Related

Can't I run multiple javascript functions with setInterval on a page?

Update
Turns out, coding while tired is not optimal. As pointed out in the comments, I was missing the definition of oneHour in countdownAutoLogout()... It must have been accidentally deleted in the copy & paste-process... Sorry for the inconvenience! I'll show myself out.
I have two almost identical countdown functions located in site.js. One is working, the other not so much.
I used to have only countdownAutoLogout(), and it was working as expected. Upon adding countdownMeeting(durationSeconds), countdownAutoLogout() is only initiated, but doesn't count down, as I have illustrated with the alert()s in the code.
countdownAutoLogout() is called in the <body>-tag in _Layout.cshtml:
<body onload="javascript: countdownAutoLogout();">
countdownMeeting(durationSeconds) is called in the scripts section in the view:
#section scripts{
<script>
$(document).ready(function() {
// Model.RemainingSeconds is a model property of type double.
countdownMeeting(#Model.RemainingSeconds);
})
</script>
}
The functions:
// Padding with leading zero:
function pad(str, max, padder) {
padder = typeof padder === "undefined"
? "0"
: padder;
return str.toString().length < max
? pad(padder.toString() + str, max, padder)
: str;
}
function countdownAutoLogout() {
alert("This alert pops up.");
var oneMinute = 60000;
var twoHours = oneMinute * 121;
var countDownDate = Date.now() + twoHours;
var x = setInterval(function () {
var now = Date.now();
var distance = countDownDate - now;
var hours = Math.floor((distance % (oneHour * 24)) / oneHour);
var minutes = Math.floor((distance % oneHour) / oneMinute);
alert("This alert doesn't pop up.");
document.getElementById("SessionCookieExpirationCountdown").innerHTML =
pad(hours, 2) + ":" + pad(minutes, 2);
if (distance < 0) {
clearInterval(x);
location.href = "/Home/Timeout";
}
}, 5000);
}
// This function is working smoothly:
function countdownMeeting(durationSeconds) {
var oneMinute = 60000;
var oneHour = oneMinute * 60;
var duration = oneMinute * durationSeconds / 60;
var countDownDate = Date.now() + duration;
var x = setInterval(function () {
var now = Date.now();
var distance = countDownDate - now;
var hours = Math.floor((distance % (oneHour * 24)) / oneHour);
var minutes = Math.floor((distance % oneHour) / oneMinute);
var seconds = Math.floor((distance % oneMinute) / 1000);
document.getElementById("MeetingDurationCountdown").innerHTML =
pad(hours, 2) + ":" + pad(minutes, 2) + ":" + pad(seconds, 2);
if (distance < 0) {
clearInterval(x);
document.getElementById("MeetingDurationCountdown").innerHTML = "Overtime!";
}
}, 1000);
}

Minutes not quite in sync with seconds

I have a timer which I am testing, it seems there is a bit of drift between when the minute countdown goes down by 1 and seconds whenever it reaches 59 seconds ()ie every minute:-
How can I alter this so they are both in sync?
my code is the following:-
$(document).ready(function() {
function now() {
return window.performance ? window.performance.now() : Date.now();
}
function tick() {
var timeRemaining = countdown - ((now() - initTick) / 1000);
timeRemaining = timeRemaining >= 0 ? timeRemaining : 0;
var countdownMinutes = Math.floor(timeRemaining / 60);
var countdownSeconds = timeRemaining.toFixed() % 60;
countdownTimer.innerHTML = countdownMinutes + ":" + countdownSeconds;
if (countdownSeconds < 10) {
countdownTimer.innerHTML = countdownMinutes + ":" + 0 + countdownSeconds;
}
if (timeRemaining > 0) {
setTimeout(tick, delay);
}
}
var countdown = 600; // time in seconds until user may login again
var delay = 20; // time (in ms) per tick
var initTick = now(); // timestamp (in ms) when script is initialized
var countdownTimer = document.querySelector(".timer"); // element to have countdown written to
setTimeout(tick, delay);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="timer"></div>
js fiddle: https://jsfiddle.net/robbiemcmullen/cer8qemt/1/
The issue is the precision is not the same for minutes and seconds.
You need to round to the nearest second before /60 / %60.
Consider: exactly 9 mins remaining:
var x = 540;
console.log(x.toFixed() % 60, Math.floor(x / 60));`
Output is: (0,9)
Then consider the call 20 ms later:
var x = 539.980;
console.log(x.toFixed() % 60, Math.floor(x / 60));
the output is now: (0, 8).
So the seconds haven't changed (yet) but the minute does.
Here is a version using setInterval and removing the use of .toFixed ()
Why do you use an interval of 20ms and not 1 second?
//method for countdown timer
$(document).ready(function() {
function now() {
return window.performance ? window.performance.now() : Date.now();
}
function tick() {
var timeRemaining = countdown - elapsedTime;
var countdownMinutes = Math.floor(timeRemaining / 60);
var countdownSeconds = timeRemaining % 60;
countdownTimer.innerHTML = countdownMinutes + ":" + countdownSeconds;
if (countdownSeconds < 10) {
countdownTimer.innerHTML = countdownMinutes + ":" + 0 + countdownSeconds;
}
++elapsedTime;
return timeRemaining;
}
var countdown = 600;
var elapsedTime = 0;
var timeRemaining;
// countdown: time in seconds until user may login again
//var delay = 20;
// delay: time (in ms) per tick
var initTick = now(); // initTick: timestamp (in ms) when script is initialized
var countdownTimer = document.querySelector(".timer");
// countdownTimer: element to have countdown written to
var interval = setInterval(function() {
if(tick() <= 0) {
clearInterval(interval);
}
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="timer"></div>
js fiddle https://jsfiddle.net/ud3wm8t1/

Timer - javascript

I have a problem with a timer in below function. How to change seconds for a minute and seconds? In present function, the timer counting only seconds and milliseconds.
if (timer === 1) {
var startTime = Date.now();
the_timer = setInterval(function() {
var elapsedTime = Date.now() - startTime;
finished_time = (elapsedTime / 1000).toFixed(3);
$("#timer").text(finished_time);
}, 44);
}
The function getTimeStr does this. It even formats it nicely so 3 seconds will be displayed as 0:03, 32 as 0:32 and 71 seconds as 1:11.
function getTimeStr(milliseconds) {
var minutes = milliseconds / 60000;
var intMinutes = Math.floor(minutes);
var seconds = Math.floor((minutes - intMinutes) * 60);
return intMinutes + ':' + (seconds < 10 ? ('0' + seconds.toFixed(0)) : seconds.toFixed(0));
}
var startTime = new Date();
setInterval(function() {
var elapsedTime = Date.now() - startTime;
console.log(getTimeStr(elapsedTime));
}, 100);

Trying to create a 24 hour timer that resets itself

This is the code I have. Very messy, but due to my inexperience I can't detect why it does not work. By my counts the Decrements are js standard, at least for the milliseconds, seconds and minutes, not sure about the hours.
Here's the code. Thanks in advance.
<!DOCTYPE html>
<html>
<body>
<span id="tHours"></span>:<span id="tMins"></span>:<span id="tSeconds"></span>:<span id="tMilli"></span>
<script>
var hours = 1;
var mins = hours * 60;
var secs = mins * 60;
var mill = secs * 100;
var currentHours = 0;
var currentSeconds = 0;
var currentMinutes = 0;
vas currentMilli = 0;
setTimeout('DecrementMilli()',100);
setTimeout('DecrementSeconds()',1000);
setTimeout('DecrementMinutes()',10000);
setTimeout('DecrementHours()',100000);
function DecrementMilli() {
currentMilli = secs % 100;
if(currentMilli <= 99) currentMilli = "000" + currentMilli;
secs--;
document.getElementById("tMilli").innerHTML = currentMilli;
if(mill !== -1) setTimeout('Decrement()',100);
}
function DecrementSeconds() {
currentSeconds = secs % 60;
if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
secs--;
document.getElementById("tSeconds").innerHTML = currentSeconds;
if(secs !== -1) setTimeout('Decrement()',1000);
}
function DecrementMinutes() {
currentMinutes = Math.round(secs / 60);
if(currentMinutes <= 60) currentMinutes = "00";
mins--;
document.getElementById("tMins").innerHTML = currentMinutes;
if(mins !== -1) setTimeout('Decrement()',10000);
}
function DecrementHours() {
currentHours = Math.round(1440 / 60);
if(currentHours <= 24) currentHours - 1;
hours--;
document.getElementById("tHours").innerHTML = currentHours;
if(hours !== -1) setTimeout('Decrement()',100000);
}
</script>
</body>
</html>
The time in your intervals is wrong. You can try the code below. Just put thee vars in your html, like:
<span id='tHours'>23</span>:<span id='tMins'>59</span>:<span id='tSeconds'>59</span>:<span id='tMilli'>99</span>
And the js like:
var milli = 99;
var sec = 59;
var min = 59;
var hour = 23;
setInterval(function () {
milli = milli == 0 ? 99 : milli - 1;
$('#tMilli').text(double0(milli));
},10);
setInterval(function () {
sec = sec == 0 ? 59 : sec - 1;
$('#tSec').text(double0(sec));
},1000);
setInterval(function () {
min = min == 0 ? 59 : min - 1;
$('#tMin').text(double0(min));
},60000);
setInterval(function () {
hour = hour == 0 ? 23 : hour - 1;
$('#tHour').text(double0(hour));
},1440000);
function double0 (num) {
num = num.toString().length == 1 ? '0' + num : num;
return num;
}
Well, I solved my own problem, but it's inelegant since it does not start at 24:00:00 but at 23:59:59. But it's a start.
I'll post it here in case it helps anyone
<script type="text/javascript">
var count = 86400;
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
}
</script>
<span id='timer'></span>

How to convert JavaScript functions to jQuery for a countdown timer on load of a page

I have the following code for a countdown timer. I need to convert the JavaScript portion to jQuery. The countdown timer starts on page load. How can I do that, as I have to load the diffTime function on load of the page. Please help me. Thanks in advance.
Edit: I got that the jquery call can not access ** function Tick() ** from ** function CreateTimer() ** . Is there any library for ** setTimeout() ** in jQuery? As I know so far, it is native to JS.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
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!")
document.getElementById("timeMsg").innerHTML = "Market closed!! ";
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;
}
function diffTime(){
var startTime = 10*60 + 30; //starting time in minute
var lastTime = 16*60 + 30; //ending time in minutes
var thisTime = new Date(); // now
var currentYear = thisTime.getFullYear();
var currentMonth = thisTime.getMonth();
var currentDay = thisTime.getUTCDate();
var currentHour = thisTime.getHours();
var currentMinute = thisTime.getMinutes();
var currentTime = currentHour*60 + currentMinute; //current time in minute
if(currentTime >= startTime && currentTime < lastTime){
var endTime = new Date(currentYear,currentMonth,currentDay,16,30); // 4:30pm
var diff = endTime.getTime() - thisTime.getTime(); // now
var remainTime = diff / (1000); // positive number of days
remainTime = Math.ceil(remainTime);
CreateTimer("timer", remainTime);
}else{
document.getElementById("timeMsg").innerHTML = "Market closed!! ";
document.getElementById("timer").innerHTML = "00:00:00";
}
}
window.onload = diffTime;
</script>
</head>
<body>
<div><span id="timeMsg">Elapsed time remain: </span><b><span id='timer'></span></b></div>
</body>
Call the function in document.ready()
$( document ).ready( function ()
{
diffTime();
});
If you want it to start after the entire (ie. images, objects, etc.) page has loaded:
$(window).load(function() {}
Otherwise you can start the timer when the HTML has been loaded & DOM is ready:
$(document).ready(function() {}

Categories