I want to get time from server for the first time and then update it by JavaScript every second. This is my code:
setInterval(function() {
var myvar = '<?php echo strtotime($now); ?>'
var hours = myvar.getHours();
var minutes = "0" + myvar.getMinutes();
var seconds = "0" + myvar.getSeconds();
myvar=hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
document.getElementById("time").innerHTML=myvar;
}, 1000);
But it has error in the second line. The error is "myvar is not a constructor". So how can I do it?
1st problem is that your PHP is echoing an integer and setting myvar to that integer. The integer doesn't have a getMinutes, getHours... function. Instead, use aDate object.
2nd problem is that your function doesn't really advance the time because every iteration, myvar is reset to the initial value (the PHP echo is only run once, before the browser downloads the page). What you need is myvar to hold the correct time every time.
3rd problem is that you're using setTimeout which only runs once. Instead you should be using setInterval which will run every second.
The solution is to set a start time outside the function, then increment it and use it each round:
//PHP will set the start time
var start = <?=time()?>;
setInterval(function(){
//add 1 second and set myvar to the correct current time
start++;
var myvar = new Date(start * 1000);
...
},1000);
You may have to make a small adjustment, because some time will elapse between when PHP writes the start value and when the JavaScript is loaded and run in the browser. This will make the JS time lag a bit behind server time.
Live demo
You can use .getHours(), .getMinutes() function only with javascript date not with php date. One way you can use is :
setInterval(function() {
var myvar = new Date();
var hours = myvar.getHours();
var minutes = "0" + myvar.getMinutes();
var seconds = "0" + myvar.getSeconds();
myvar=hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
document.getElementById("time").innerHTML=myvar;
}, 1000);
if you use php you can't update the time
strtotime returns a integer that represents the current time.
You're storing that in a variable, as an string.
Your compiled php file will look something like this:
setInterval(function() {
var myvar = '1468845612'
myvar is just a ordinary string, there. That string doesn't have an .getHours function.
replace that var myvar line with this:
var myvar = new Date(<?php echo strtotime($now); ?>000);
Rendered output:
var myvar = new Date(1468845612000);
Notice how I added the 000 in there.
strtotime returns a timestamp in seconds. JavaScript's Date constructor expects a timestamp in milliseconds.
That all said, the setInterval call is pointless.
The php snippet will run only once, on page load. Then the interval will show the same date every second it's executed.
Related
I am sending a timestamp from the server and I want the browser to know when that exact time is.
I am using Moment but feel there are a few ways to achieve this.
I have looked at using isSame() in a setInterval() but it doesn't seem to be working.
var interval = setInterval(function(){
if(moment().isSame(moment(data.server_time_stamp))){
console.log('MATCHES!!!')
clearInterval(interval)
}
}, 1)
Where data.server_time_stamp is a moment object passed from the server (Calculated as current time + 10 seconds). I have set this to utc() in order to standardize the timezones on server and client.
I have also tried setting it to unix() and in my setInterval() loop, using === operator to see if they are the same. Like so:
var interval = setInterval(function(){
if(cur_time === data.screenshot_time){
console.log('MATCHES!!!')
clearInterval(interval)
}
}, 1)
all though with this method, it doesn't seem to be acurate enough.
What is the most accurate way to messure this?
You should compare the seconds not the milliseconds like #some said.
It could work like that:
moment.utc().isSame(moment(data.server_time_stamp), 'second');
The method I ended up using (but am yet to thoroughly test) was using timesync to sync all clocks and then match the current time in a setInterval()
var ts = timesync.create({
server: SERVER + '/timesync'
});
var interval = setInterval(function(){
if(moment(ts.now()).utc().unix() === data.screenshot_time){
console.log('SNAPPED!!!')
take_photo()
clearInterval(interval)
}
}, 1)
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 5 years ago.
I want to auto update function time() in javascript and I have write this code:
var time = null;
setInterval(function() {
time = Date();
}, 1000);
console.log(time);
But it shows me null in console.log. I want to get auto-updated function time() in variable time
What is wrong?
Lets break down the question
<?php echo time() ?> This is generated server-side and cannot be re-calculated in the client side (where your code actually runs).
var time = <?php echo time() ?>; Here you are re-declaring (and by this masking) the original time variable.
console.log(time); This is being called outside of the interval function scope, so it will only run once (and in that time in will print null).
You are looking for something like this :
setInterval(function(){
console.log(Date())
}, 1000);
If you want your variable to be accessiable outside the interval's function's scope you can do something like this
var time;
setInterval(function(){
time = Date();
console.log(time);
}, 1000);
// Now the 'time' variable will be accessible and will hold the latest date value
// For example console.log(time)
And of course you can replace Date() with any date/time creating function you will need for you specific purposes.
You defined new timer variable and didn't override your global variable .
Also your console.log is outside of the interval scope so you print the value before it was change.
The following code work:
var time = null;
setInterval(function() {
time = "test";
console.log(time);
}, 1000);
How to get Time with Cookies javascript When I close the tab or Page?
i'm try use window.onunload but time can not be stored in cookies..
in this code i'm push my cookies to be array
setCookie("time",time,1)
window.onunload =function (){
var set = getCookie('time');
var arr = [];
var push = arr.push(set);
console.log (arr);
return arr;
}
In JavaScript, there is a class called "Date" that let's you get the current time.
var d = new Date(); creates a new Date object and assigns it to the variable d
Now, you have the date and time - you can do whatever you like.
For example: document.getElementById('foo').innerHTML = d.toString() finds the element with the ID of "foo" and sets it's contents to the date and time.
Keep in mind that this date and time display will not constantly update itself. You will have to do that with some timed recursion.
There are many more things you can do with dates. Remember, Google is your friend - look up some things about the Date object.
I am using setInterval in Javascript. For a simple example I tried to update a time displayed.
var tim = new Date();
function loadLog(){
document.getElementById('timebox').innerHTML=tim.getTime();
}
window.setInterval(loadLog, 1000);
But the time is not updated. Why? How can I update the variable inside setInterval?
Thanks
Generate a new date each time instead of always showing the same one :
function loadLog(){
var tim = new Date();
document.getElementById('timebox').innerHTML=tim.getTime();
}
window.setInterval(loadLog, 1000);
I want to do something like
var date = new Date();
var pretime = date.getTime();
$.post(
"ajaxfile.php",
object,
function(data) {
var totalTime = date.getTime()-pretime;
$("#feed").append("Time: " + totalTime + "<br/>" + pretime + "<br/>" + date.getTime() + "<br/>");
});
});
That is, measure how long the AJAXcall lasts before I get a response. But the print from this callback function is:
Time: 0
1326184886814
1326184886814
What is the solution to this?
getTime() is returning the same value because you are reusing the same Date() object. You need to create a new Date object:
var date = new Date();
var pretime = date.getTime();
$.post("ajaxfile.php", object, function(data){
var date2 = new Date();
var totalTime = date2.getTime()-pretime;
$("#feed").append("Time: " + totalTime + "<br/>" + pretime + "<br/>" + date.getTime() + "<br/>");
});
});
I'm no Javascript expert, but it seems to me that you're creating a single Date object which (if it's similar to Java's Date object) stores the date/time at the point it was created, and then using that same date object twice - i.e. comparing the start date/time to itself.
Try creating a second Date object inside the AJAX callback function to capture the end time.
If you are just interested in the time, without saving it somewhere, you can use Google Chrome's developer console.
press F12, go to "Network" tab, execute your Ajax call, and you can see a timeline of how long it takes you to get a response.
If you use firebug to debug your Javascript code take a look at the console. It will tell you how many miliseconds your ajax call takes :)
Also, if you don't use firebug, what are you waiting for? It is awesome for debugging and will save you lots of time!