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+.
Related
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
I'm getting date from the API in this format 14:30:00 inside "this.StartTime". My question is how can I calculate the time difference between the date I'm getting inside "this.StartTime" and present date?
Following is my component.ts code:-
getBookingDetails() {
this._CounsellingService.getBookingDetails().subscribe(
response => {
this.sessionDetails = response;
this.StartTime = this.sessionDetails.StartTime;
}
);
}
You can create a date today and then set its time part as startDate. Then compare it with current time;
var startTime = "14:30:00".split(":");
var h = startTime[0];
var m = startTime[1];
var s = startTime[2];
var now = new Date();
startTime = new Date(now);
startTime.setHours(h);
startTime.setMinutes(m);
startTime.setSeconds(s);
difference = startTime.getTime() - now.getTime();
console.log(msToTime(difference))
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}
I am trying to make a simple plugin to calculate date and time by this code:
<div id="timer"></div>
<script>
$.fn.timeCounter = function(time) {
var target = new Date(time);
var now = new Date();
var timeDiff = target.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#timer").append( "<p>"+days+"</p>" );
$("#timer").append( "<p>"+hours+"</p>" );
$("#timer").append( "<p>"+minutes+"</p>" );
$("#timer").append( "<p>"+seconds+"</p>" );
var timer = setTimeout('timeCounter',1000);
};
$("#timer").timeCounter("june 16, 2014 00:01:00");
</script>
the code is working fine but I am having problem on displaying actual count down on numbers! can you please let me know how to fix this?
Thanks
Following displays count down in seconds:
$.fn.timeCounter = function(time) {
var target = new Date(time);
var now = new Date();
var timeDiff = target.getTime() - now.getTime();
// count down logic
setTimeout(function cdtd(){
if (timeDiff > 0){
// reduce one seconds
timeDiff-=1000;
// change this to a more dedicated display per your requirements
$('#timer').html(timeDiff/1000);
// next one second, reference to cdtd
setTimeout(cdtd,1000);}
},1000);
}
See working sample:
http://jsfiddle.net/danyu/X33kv/
I found a JSFiddle with a timer that counts up every second.
Except i want this to work with just the minutes and seconds. No hours.
Any ideas?
DATE_OBJ.getSeconds() to get seconds of Date object.
DATE_OBJ. getMinutes() to get minutes of Date object.
setInterval to invoke handler function after every second(1000ms).
var handler = function() {
var date = new Date();
var sec = date.getSeconds();
var min = date.getMinutes();
document.getElementById("time").textContent = (min < 10 ? "0" + min : min) + ":" + (sec < 10 ? "0" + sec : sec);
};
setInterval(handler, 1000);
handler();
<h1 id="time" style="text-align: center"></h1>
Here's a very hackish approach - http://jsfiddle.net/gPrwW/1/
HTML -
<div id="worked">31:14</div>
JS :
$(document).ready(function (e) {
var $worked = $("#worked");
function update() {
var myTime = $worked.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(0);
dt.setMinutes(ss[0]);
dt.setSeconds(ss[1]);
var dt2 = new Date(dt.valueOf() + 1000);
var temp = dt2.toTimeString().split(" ");
var ts = temp[0].split(":");
$worked.html(ts[1]+":"+ts[2]);
setTimeout(update, 1000);
}
setTimeout(update, 1000);
});
The precise way of handling this is the following:
store the time of the start of the script
in a function that gets called repeatedly get the time elapsed
convert the elapsed time in whatever format you want and show it
Sample code:
var initialTime = Date.now();
function checkTime(){
var timeDifference = Date.now() - initialTime;
var formatted = convertTime(timeDifference);
document.getElementById('time').innerHTML = '' + formatted;
}
function convertTime(miliseconds) {
var totalSeconds = Math.floor(miliseconds/1000);
var minutes = Math.floor(totalSeconds/60);
var seconds = totalSeconds - minutes * 60;
return minutes + ':' + seconds;
}
window.setInterval(checkTime, 100);
You can easily change the granularity of checking the time (currently set at 0.1 seconds). This timer has the advantage that it will never be out of sync when it updates.
You can make a function that increments a counter every time it's called, shows the value as:
counter/60 minutes, counter%60 seconds
Then you can use the setInterval function to make JavaScript call your code every second. It's not extremely precise, but it's good enough for simple timers.
var initialTime = Date.now();
function checkTime(){
var timeDifference = Date.now() - initialTime;
var formatted = convertTime(timeDifference);
document.getElementById('time').innerHTML = '' + formatted;
}
function convertTime(miliseconds) {
var totalSeconds = Math.floor(miliseconds/1000);
var minutes = Math.floor(totalSeconds/60);
var seconds = totalSeconds - minutes * 60;
return minutes + ':' + seconds;
}
window.setInterval(checkTime, 100);
This might be something?
plain count up timer in javascript
It is based on the setInterval method
setInterval(setTime, 1000);
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() {}