Running a real-time clock with AJAX - javascript

Now that I was helped getting AJAX running just great, I'm having problems running a clock function with it....
Clock code (located in the head):
<script type="text/javascript">
var ampm = "AM"; //Default
var message="";
function startTime()
{
var today = new Date(); //Number goes here
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);
h=checkTime2(h);
document.getElementById('clocktxt').innerHTML=h+":"+m+":"+s+ " " +ampm + " " + message;
//t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
message = "How long you gonna sit there?";
}
return i;
}
function checkTime2(i)
{
if (i>12)
{
i=i-12;
ampm="PM";
}
return i;
}
//setInterval(startTime,1000);
</script>
AJAX code (bottom of the document):
<script type='text/javascript'>
function CheckForChange(){
//alert("<?echo (count($listArray)) . ' and ' . count(file($filename_noformat))?>");
//if (<?echo count($listArray)?> == <?echo count(explode("\n", $filename_noformat))?>){
//setInterval("alert('Yup, it is 1')", 5000);
//alert('Now it is changed');
//}
var ajaxReady = new XMLHttpRequest();
ajaxReady.onreadystatechange = function(){
if (ajaxReady.readyState == 4){
//Get the data
//document.getElementById('clocktxt').innerHTML = ajaxReady.responseText;
//startTime();
//alert("here");
//alert(ajaxReady.responseText);
}
}
ajaxReady.open("GET","ServerTime.php",true);
ajaxReady.send(null);
}
setInterval(CheckForChange(), 1000);
setInterval(startTime(),1000);
</script>
What I'm trying to do is pass the input from ServerTime.php which is just a count of milliseconds from Unix epoch, into the clock, so the clock is being updated by the AJAX every second and the clock function runs with a new starting value each second.... I used to have parameters for the clock function before I realized the clock wasn't even getting called.
What do you think is wrong? I'm guessing it has something to do with the clock and the caller of the clock being in two different script tags, but I can't think of how to get around it. For some reason when I moved the AJAX part into the same script tag, following the clock, nothing happens.
To Kolink: I have this
function getTheNow(){
TIMESTAMP = <?php echo time(); ?>000;
offset = new Date().getTime()-TIMESTAMP;
setInterval(function() {
var now = new Date();
now.setTime(now.getTime()-offset);
// print out the time according to the variable `now`
//alert(now);
},5000);
return now;
}
function startTime()
{
var now = getTheNow;
//alert(now);
var today = new Date(); //Number goes here
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);
h=checkTime2(h);
document.getElementById('clocktxt').innerHTML=h+":"+m+":"+s+ " " +ampm + " " + message;
t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
message = "How long you gonna sit there?";
}
return i;
}
function checkTime2(i)
{
if (i>12)
{
i=i-12;
ampm="PM";
}
return i;
}
setInterval(startTime,1000);

Computer clocks are not so inaccurate that you have to re-sync them every second. Try every ten minutes, or even every hour.
In fact, I just do away with synchronising altogether. It is far easier to do this:
<script type="text/javascript">
TIMESTAMP = <?php echo time(); ?>000;
offset = new Date().getTime()-TIMESTAMP;
setInterval(function() {
var now = new Date();
now.setTime(now.getTime()-offset);
// print out the time according to the variable `now`
},1000);
</script>

JavaScript 101 error
setInterval(CheckForChange(), 1000);
setInterval(startTime(),1000);
You are not assigning the function, you are calling/executing them and saying what ever is returned from these functions should be set. Drop the () so you are referencing the functions.
setInterval(CheckForChange, 1000);
setInterval(startTime,1000);

Related

flaws in second's field increment in stop watch

<script>
var s=0;
var ms=0;
function timeDisp()
{
var d = new Date();
ms = d.getMilliseconds();
if(ms==999 && s<60)
{
s=s+1;
ms=0;
}
var r = (((s <10)?"0":":") + s + (":") + ms);
return r;
}
function display()
{
var t = timeDisp();
document.getElementById("time").value=t; //time is id of input text field
m=setTimeout('display()',1);
}
function stop()
{
clearTimeout(m);
}
</script>
I have written this code to create simple stop watch but there is flaw in increment in seconds field.Sometimes second do not increase as it should and sometime it skip one or two seconds while running.

Time Interval seconds run fast on tab changed Javascript

I have an issue that hold my neck with time interval. I am calculating my time/clock one second at a time with the function below.
Header.prototype= {
time_changed : function(time){
var that = this;
var clock_handle;
var clock = $('#gmtclock');
that.time_now = time;
var increase_time_by = function(interval) {
that.time_now += interval;
};
var update_time = function() {
clock.html(moment(that.time_now).utc().format("YYYY-MM-DD HH:mm") + " GMT");
};
update_time();
clearInterval(clock_handle);
clock_handle = setInterval(function() {
increase_time_by(1000);
update_time();
}, 1000);
},
};
The above works fine and increase my time a second at a time correctly . However. I added another event that fires on web changed or tab navigated.
var start_time;
var tabChanged = function() {
if(clock_started === true){
if (document.hidden || document.webkitHidden) {
start_time = moment().valueOf();
time_now = page.header.time_now;
}else {
var tnow = (time_now + (moment().valueOf() - start_time));
page.header.time_changed(tnow);
}
}
};
if (typeof document.webkitHidden !== 'undefined') {
if (document.addEventListener) {
document.addEventListener("webkitvisibilitychange", tabChanged);
}
}
The above fires when ever user leave the page and comes back . It add the delay to the time. However, i notice the second increase rapidly . and very past my timer does not fire very second any more as specified in the clock hand. It add second every milliseconds and fats. Please why this and how do i fix this ? My time run fast and ahead when ever i change tab and returned . Any help would be appreciated
Update
Below is my WS request function.
Header.prototype = {
start_clock_ws : function(){
var that = this;
function init(){
clock_started = true;
WS.send({ "time": 1,"passthrough":{"client_time" : moment().valueOf()}});
}
that.run = function(){
setInterval(init, 900000);
};
init();
that.run();
return;
},
time_counter : function(response){
var that = this;
var clock_handle;
var clock = $('#gmt-clock');
var start_timestamp = response.time;
var pass = response.echo_req.passthrough.client_time;
that.time_now = ((start_timestamp * 1000) + (moment().valueOf() - pass));
var increase_time = function() {
that.time_now += (moment().valueOf() - that.time_now);
};
var update_time = function() {
clock.html(moment(that.time_now).utc().format("YYYY-MM-DD HH:mm") + " GMT");
};
update_time();
clearInterval(clock_handle);
clock_handle = setInterval(function() {
increase_time();
update_time();
}, 500);
},
};
and in my WS open event
if(isReady()=== true){
if (clock_started === false) {
page.header.start_clock_ws();
}
}
In my WS onmessage event
if(type ==='time'){
page.header.time_counter(response);
}
Base on your suggestion, i modified my increase_time_by to
var increase_time_by = function() {
that.time_now += (moment().valueOf() - that.time_now);
};
It seems fine now. Would test further and see.
Instead of incrementing the clock by the value of the interval, just update the clock to the current time with each pass. Then it won't matter if you fire exactly 1000 ms apart or not.
You actually may want to run more frequently, such as every 500 ms, to give a smoother feel to the clock ticking.
Basically, it comes down to the precision of the timer functions, or lack thereof. Lots of questions on StackOverflow about that - such as this one.
Based on your comments, I believe you are trying to display a ticking clock of UTC time, based on a starting value coming from a web service. That would be something like this:
var time_from_ws = // ... however you want to retrieve it
var delta = moment().diff(time_from_ws); // the difference between server and client time
// define a function to update the clock
var update_time = function() {
clock.html(moment.utc().subtract(delta).format("YYYY-MM-DD HH:mm") + " GMT");
};
update_time(); // set it the first time
setInterval(update_time, 500); // get the clock ticking

Jquery/Ajax/JavaScript Time Count Down Non-Stop

Can anyone give me Jquery function for Time Count Down , but work like this.
Time every 15 minutes (without stop).
When time is 0, do some Ajax update function and auto start again (Without click or refresh by myself)
The time like (TimeCountDown = TimeNow - (TimeNow+15minuts)).
I just can't find functions like this, and i don't know how to work with time.
Thanks for help.
var _TimerCount = 15;
var _Timer = setInterval(function(){
TimerCountDown();
},6000);
function TimerCountDown(){
if(_TimerCount !=0){
_TimerCount -=1;
}
else{
var currentdate = new Date();
var _DateString = currentdate.getDate() + " " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();
_TimerCount = 15;
$.get("C# CODE FILE HERE eg. MyFile.ashx",{_DateTime:_DateString }).done(function(response){
//Your Response CODE HERE
alert(response);
});
}
}
I'm a little unclear on what you are trying to do.
I think you want something like this:
var timeOut = function() {
****Whatever you want the code to do every 15 minutes****
};
var main = function() {
setInterval(timeOut, 900000);
};
$(document).ready(main);
Note: time is in miliseconds so 1 second = 1000
JSFiddle: http://jsfiddle.net/kitsonbroadhurst/552nu/1/

javascript countdown synchronize on different browsers

I'm sorry if this question is a bit tricky but I have no other way of asking it and I am an absolute noob in javascript world.
I have this javascript counter that someone helped me to gather on stackoverflow and it works fine BUT
the countdown timer will start from the beginning on a different browsers.
i.e. when I look at it on Firefox, it will carry on counting down and it will keep working as it should. lets say the timer is set to countdown a day. on Firefox it will show 23:24 hours/minutes left but if I open a new browser (any browser), it will show the timer 23:59 hours/minutes left and it will start counting down from there... even though the countdown timer was already running on the same page!!
here is the code:
<script type="text/javascript">
var EXPIRY = parseInt(new Date().getTime()/1000) + 24*60*60;
var counter = null;
var counter_interval = null;
function setCookie(name,value,days) {
console.log("setting "+name+" "+value);
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else {
expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length,c.length);
}
}
return null;
}
function deleteCookie(name) {
setCookie(name,"",-1);
}
function resetCounter() {
EXPIRY = parseInt(new Date().getTime()/1000) + 24*60*60;
}
function stopCounter() {
window.clearInterval(counter_interval);
deleteCookie('Expiry');
}
function updateCounter() {
var msg = '';
curTime = parseInt(new Date().getTime()/1000);
if (curTime < EXPIRY) {
msg = convertSecondsToDays(EXPIRY - curTime);
}
else {
EXPIRY = parseInt(new Date().getTime()/1000) + 24*60*60;
}
var el = document.getElementById('counter');
if (el) {
el.innerHTML = msg
}
}
function convertSecondsToDays(sec) {
var days, hours,rem,mins,secs;
days = parseInt(sec/(24*3600));
rem = sec - days*3600
hours = parseInt(rem/3600);
rem = rem - hours*3600;
mins = parseInt(rem/60);
secs = rem - mins*60;
return days +":" + hours +":"+mins + ":"+ secs + "";
}
function startCounter() {
stopCounter();
setCookie('Expiry', EXPIRY, 1);
counter_interval = window.setInterval(updateCounter, 1000);
}
function init() {
EXPIRY = getCookie('Expiry');
if (!EXPIRY) {
console.log("unable to find cookie");
resetCounter();
}
startCounter();
}
init();
</script>
you can view it on the fiddle here: http://jsfiddle.net/h2DEr/1/
how can i make it in a way that it will show the same time left on all the browsers as it will be displayed on the same page?
Thanks
Edit:
I found this code which works with mysql. it works fine but instead of counting down it will show how many days/hours/minutes the product/item was posted on the site. and this doesn't need any javascript as is...
This is sort of what I am looking for but instead of counting up it needs to countdown:
<?php
//list fields and convert to seconds
$countdown['days']=(5) * 24 * 60 * 60;
$countdown['hours']=(3) * 60 * 60;
// etc, etc
$countsum=time() + $countdown['days'] + $countdown['hours']; //and so on
// the above would be the timestamp to enter into the table
##########
// 'dumbed down' query
include "config/connect_to_mysql.php";
$result=mysql_query("SELECT * FROM tomProduct WHERE id='id';");
while ($row=mysql_fetch_assoc($result))
$time=$row['date_added'] - time(); //this field would be a PHP timestamp (time())
$count=getdate($time);
$x=getdate(); //todays information
$count['mday'] -= $x['mday'];
$count['hour'] -= $x['mday'];
$count['minutes'] -= $x['minutes'];
echo "$count[mday] Days $count[hour] Hours $count[minutes] Minutes"; //etc
// untested, but should work
?>
JavaScript is always running on the client. One instance of the timer has no knowledge of any other instance running elsewhere.
To synchronize time between different browsers, you would need server-side scripts.
Using expiration-time-stamps in a server-side script in conjunction with JavaScript timers should give you the synchronization you are looking for.
Cookies are not transferred from browser to browser. They are stored in the web browser.

Countdown timer for use in several places at same page

I want to make a countdown timer, that can be used on several places in the same page - so I think it should be a function in some way.
I really want it to be made with jQuery, but I cant quite make it happen with my code. I have e.g. 10 products in a page, that I need to make a countdown timer - when the timer is at 0 I need it to hide the product.
My code is:
$(document).ready(function(){
$(".product").each(function(){
$(function(){
var t1 = new Date()
var t2 = new Date()
var dif = t1.getTime() - t2.getTime()
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var count = Seconds_Between_dates;
var elm = $(this).attr('id');
alert(elm);
countdown = setInterval(function(){
$(elm + " .time_left").html(count + " seconds remaining!");
if (count == 0) {
$(this).css('display','none');
}
count--;
}, 1000);
});
});
});
EDIT 1:
$(document).ready(function(){
$(".product").each(function(){
var elm = $(this).attr('id');
$(function(){
var t1 = new Date()
var t2 = new Date()
var dif = t1.getTime() - t2.getTime()
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var count = Seconds_Between_dates;
alert(elm);
countdown = setInterval(function(){
$(elm + " .time_left").html(count + " seconds remaining!");
if (count == 0) {
$(this).css('display','none');
}
count--;
}, 1000);
});
});
});
Do you have any solutions to this?
I'd probably use a single interval function that checks all the products. Something like this:
$(function() {
/* set when a product should expire.
hardcoded to 5 seconds from now for demonstration
but this could be different for each product. */
$('.product').each(function() {
$(this).data('expires', (new Date()).getTime() + 5000);
});
var countdown_id = setInterval(function() {
var now = (new Date()).getTime();
$('.product').each(function() {
var expires = $(this).data('expires');
if (expires) {
var seconds_remaining = Math.round((expires-now)/1000);
if (seconds_remaining > 0) {
$('.time-left', this).text(seconds_remaining);
}
else {
$(this).hide();
}
}
});
}, 1000);
});
You could also cancel the interval function when there is nothing left to expire.
Your problem seems to be that this doesn't refer to the current DOM element (from the each), but to window - from setTimeout.
Apart from that, you have an unnecessary domReady wrapper, forgot the # on your id selector, should use cached references and never rely on the timing of setInterval, which can be quite drifting. Use this:
$(document).ready(function(){
$(".product").each(function(){
var end = new Date(/* from something */),
toUpdate = $(".time_left", this);
prod = $(this);
countDown();
function countdown() {
var cur = new Date(),
left = end - cur;
if (left <= 0) {
prod.remove(); // or .hide() or whatever
return;
}
var sec = Math.ceil(left / 1000);
toUpdate.text(sec + " seconds remaining!"); // don't use .html()
setTimeout(countdown, left % 1000);
}
});
});

Categories

Resources