Javascript setInterval doesn't update timestamp used inside - javascript

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);

Related

Auto refresh function in javascript [duplicate]

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);

get time from php and update by javascript

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.

JS objects for Timer on Webpage

What are the objects in JavaScript that we use for running time on webpage?
I tried using getElementId() method and could not do it.
If you want to get the current date and time,
var now = new Date()
var deadline = new Date(now.getFullYear, now.getMonth, now.getDate, now.getHours, now.getMinutes + 15);
Then you can fill an element with the deadline variable.
See here
https://blog.smalldo.gs/2013/12/create-simple-countdown/

Get time using cookies javascript

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.

Is it possible to apply a callback function to "new Date" using prototype

I want to add 1 hour to every Date it created using prototype and now I got this:
Date.prototype.addOneHr = function (){
this.setTime(this.getTime()+1*1000*60*60);
}
However, I have to call it every new Date():
var date=new Date();
data.addOneHr();
It is very inconvenient and it gives me more mess. D:
So I am thinking that if there is a way to call addOneHr() every time I created a new Date, so that it won't give me headaches when editing the JavaScript.
Any solutions are welcomed. Thanks.
You can't do what you're asking, but you could make it a little better by altering your function slightly:
Date.prototype.addOneHr = function() {
this.setTime(this.getTime() + 1000 * 60 * 60);
return this;
}
By having it return the object, you can write code like this:
var a_date = new Date().addOneHr();
I would strongly recommend against modifying Date's prototype to construct a date in the way you want it (this includes adding code to fire a callback function off when the Date is created).
Someone coming along and looking at your code will not immediately realize why all new Date()s are one hour in the future.
Instead, why not create a helper function that returns the Date you want and call it from everywhere instead:
function createDate() {
var now = new Date();
now.setHours(now.getHours() + 1);
return now;
}
...
var date = createDate();
If you're going to change the behaviour of a class then you risk confusing anyone else who looks at your code and doesn't expect it to work so differently. To follow the classical OOP pattern you must, of course, create a descendent.
DatePlusOneHour = Object.Extend(Date, {
getTime: function() {
return Date.prototype.getTime.call(this) + 1000*60*60;
}
});
You might need to override more functions than just getTime or perhaps you can override the constructor this way. I'm sure you understand what to do next.

Categories