Countdown midnight server with PHP, vanilla js and Ajax - javascript

Okay i am trying once again since last time my post got flagged as a duplicate of something entirely different than what i were asking so basically the quick stackof'ers who does this to vannilla/php questions ruined my post and i got no valid answers...
This is not a jQuery question...
This is not a Ajax response question...
(I even found my own post as googles 1st result when trying to find answers for my question)
Sample here
Basically i made a midnight countdown timer in Javascript which works perfectly...
I am trying to make it countdown to midnight of server and not the local machine, so i did a Ajax call where i echo getTime(); and i am trying to put this.responseText inside where i used now.getTime();
Javascript/Ajax
(function () {
var serverMilli = document.getElementById("serverMilli");
var serverCountdown = document.getElementById("serverCountdown");
var machineMilli = document.getElementById("machineMilli");
var machineCountdown = document.getElementById("machineCountdown");
let serverTime;
var http = new XMLHttpRequest();
var url = "time.php";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
serverTime = this.responseText;
serverMilli.textContent = this.responseText;
}
;
};
http.send();
function countDownServer() {
var now = new Date();
var currentTime = serverTime - now.getTime();
var eventDate = new Date();
eventDate.setDate(now.getDate() + 1);
eventDate.setHours(24);
eventDate.setMinutes(0);
eventDate.setSeconds(0);
eventDate.setMilliseconds(0);
var eventTime = eventDate.getTime();
var remainingTime = eventTime - currentTime;
var sekunder = Math.floor(remainingTime / 1000);
var minutter = Math.floor(sekunder / 60);
var timer = Math.floor(minutter / 60);
sekunder %= 60;
minutter %= 60;
timer %= 24;
sekunder = (sekunder < 10) ? "0" + sekunder : sekunder;
minutter = (minutter < 10) ? "0" + minutter : minutter;
timer = (timer < 10) ? "0" + timer : timer;
var testServer = timer + ":" + minutter + ":" + sekunder;
serverCountdown.textContent = testServer;
setTimeout(countDownServer, 1000);
}
countDownServer();
function countDownMachine() {
var now = new Date();
var currentTime = now.getTime();
machineMilli.textContent = currentTime;
var eventDate = new Date();
eventDate.setDate(now.getDate() + 1);
eventDate.setHours(24);
eventDate.setMinutes(0);
eventDate.setSeconds(0);
eventDate.setMilliseconds(0);
var eventTime = eventDate.getTime();
var remainingTime = eventTime - currentTime;
var sekunder = Math.floor(remainingTime / 1000);
var minutter = Math.floor(sekunder / 60);
var timer = Math.floor(minutter / 60);
sekunder %= 60;
minutter %= 60;
timer %= 24;
sekunder = (sekunder < 10) ? "0" + sekunder : sekunder;
minutter = (minutter < 10) ? "0" + minutter : minutter;
timer = (timer < 10) ? "0" + timer : timer;
var testMachine = timer + ":" + minutter + ":" + sekunder;
machineCountdown.textContent = testMachine;
setTimeout(countDownMachine, 1000);
}
countDownMachine();
})();

All i had to do was to do time() * 1000 because time() returns seconds and .getTime() returns milliseconds... waow cant believe i oversaw this and had so many problems, cant believe none from stf dident see this xD

Related

Javascript Countdown timer using SQL variable

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>

How to get servers time

Okay so i need a countdown to the servers midnight because when the server reach midnight it will run a cronjob which is relevant to the users so they need to see how many hours that are left untill it is midnight on the server and not in their own timezone.
Sample page here
The date_default_timezone_get(); is europe/copenhagen
PHP
(The page the Ajax is requesting)
echo time() * 1000;
Javascript
(function () {
var test = document.getElementById("test");
var difference = document.getElementById("difference");
var serverMilli = document.getElementById("serverMilli");
var serverCountdown = document.getElementById("serverCountdown");
var machineMilli = document.getElementById("machineMilli");
var machineCountdown = document.getElementById("machineCountdown");
let serverTime;
var localTime;
var http = new XMLHttpRequest();
var url = "time.php";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
serverTime = this.responseText;
}
;
};
http.send();
function countDownServer() {
var now = new Date();
var localTime = now.getTime();
var currentDiff = serverTime - localTime;
var currentTest = serverTime - currentDiff;
var currentTime = currentTest;
var eventDate = new Date();
eventDate.setDate(now.getDate() + 1);
eventDate.setHours(24);
eventDate.setMinutes(0);
eventDate.setSeconds(0);
eventDate.setMilliseconds(0);
var eventTime = eventDate.getTime();
var remainingTime = eventTime - currentTime;
var sekunder = Math.floor(remainingTime / 1000);
var minutter = Math.floor(sekunder / 60);
var timer = Math.floor(minutter / 60);
sekunder %= 60;
minutter %= 60;
timer %= 24;
sekunder = (sekunder < 10) ? "0" + sekunder : sekunder;
minutter = (minutter < 10) ? "0" + minutter : minutter;
timer = (timer < 10) ? "0" + timer : timer;
var testServer = timer + ":" + minutter + ":" + sekunder;
serverCountdown.textContent = testServer;
setTimeout(countDownServer, 1000);
}
countDownServer();
})();
Everything "kinda" works... the problem is if i change the timezone on my computer it will display longer hours untill midnight than it really is on the server?
How is this possible when the timezone on server is europe/copenhagen and i use time() ? should it not use the servers timezone?
No as javascript executes in your browser, it will use the timezone of your computer.
You have to tell javascript which timezone you would like (if not your one)
I found this for you:
How to get Time of specific timezone using javascript?
The JavaScript Date object always uses the user's computer time. You can use a library like Moment Timezone to set a different timezone that can be calculated on the client.
Otherwise you can try and calculate the difference between the server time and local time, but it might be off by an hour a couple times per year due to differences in DST.

show time in HH:MM only in this javascript code [duplicate]

This question already has answers here:
Current time formatting with Javascript
(16 answers)
Closed 8 years ago.
The following JS shows the time in HH:MM:SS format while I need it to show HH:MM only
setInterval(function() {
var d = new Date();
var t = d.getTime();
var interval = 5*60*1000;
var last = t - t % interval;
var next = last + interval + 10*60000;
d.setTime(next);
var time = d.toLocaleTimeString();
$(".clock").html(time);
}, 1000);
Any idea on how to achieve that?
Fiddle: http://jsfiddle.net/7z9boag8/
There's getHours() and getMinuets() methods available.
example:
http://jsfiddle.net/0todu2y7/
jQuery(function($) {
setInterval(function() {
var d = new Date();
var t = d.getTime();
var interval = 5*60*1000;
var last = t - t % interval;
var nextt = last + interval + 5*60000;
d.setTime(nextt);
var hours = d.getHours();
var min = d.getMinutes();
$(".clock").html(hours+":"+min);
}, 1000);
});
i am sorry . i m not edit your code . i just give you another procedure
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
var time = hours+':'+minutes+':'+seconds;
return time;
}
Second Formula is
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function yourTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
yourTime();
Try this:
var time = d.toLocaleTimeString().match(/(\d+:\d+):\d+( \w{2})*/);
var time = time[1] + (time[2] ? time[2] : "");
setInterval(function() {
var d = new Date();
var t = d.getTime();
var interval = 5*60*1000;
var last = t - t % interval;
var next = last + interval + 10*60000;
d.setTime(next);
var time = d.toLocaleTimeString().split(':')
time.pop()
time.join(':')
$(".clock").html(time);
}, 60000);
I don't think that u shuold run tins function every second. U may do it once in minute.

A count up timer doesn't setup error

A count up timer that won't reset on refresh
var test;
var pageVisisted = new Date();
test = setInterval(function () {
var timeOnSite = new Date() - pageVisisted;
var secondsTotal = timeOnSite / 1000;
var minutes = Math.floor(secondsTotal / 60) % 3600;
var seconds = Math.floor(secondsTotal) % 60;
document.getElementById('counter').innerHTML = minutes + "." + seconds;
}, 1000);
I am spending lot of hours to setup the timer.But cannot able to done it.Anybody know how to solve these kind of Errors.
For Example:
If I refresh these page at 1.26 seconds,countdown again started as 0.But it have to started at 1.26 after refresh.Can you solve that and tell me how to fix it.
You can store pageVisited value in localStorage (or better I guess in sessionStorage):
var pageVisited = +localStorage.pageVisited || +new Date();
var test = setInterval(function() {
var timeOnSite = new Date() - pageVisited;
var secondsTotal = timeOnSite / 1000;
var minutes = Math.floor(secondsTotal / 60) % 3600;
var seconds = Math.floor(secondsTotal) % 60;
document.getElementById('counter').innerHTML = minutes + "." + seconds;
}, 1000);
if (!localStorage.pageVisited) {
localStorage.pageVisited = pageVisited;
}
Demo: http://jsfiddle.net/HjxLX/
If you want the timer to be cleared after you close the browser window use sessionStorage.
IE support: IE8+.

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