Auto refresh function in javascript [duplicate] - javascript

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

Related

How to tell if current time is the exact same as timestamp right down to the millisecond?

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)

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.

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.

Javascript setInterval doesn't update timestamp used inside

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

Create a time interval that will cause a function to run at a random time in JavaScript

I am trying to load a random image at a random time. For some reason this is not randomizing the time, though it does randomize the image. Any ideas what's wrong?
var randomTime2 = 3000; //initialize the random time with this value to start
setInterval(function(){
var randomNum = Math.floor((Math.random()*3)+1);//random num for image
$('.recent-project2 img').fadeTo('slow',0,function(){
var randomImg = "img/recent-projects-"+randomNum+".jpg";
$('.recent-project2 img').attr('src',randomImg);
$('.recent-project2 img').fadeTo('slow',1);
});
randomTime2 = Math.floor(Math.random()*10000);//reset random time
return randomTime2; //return random time
},randomTime2);
Use setTimeout and re-trigger at the end of the function with a random time.
The setInterval call will just add your function and the required interval to an internal table to remember to call your code when the expected delay period passed. Note however that even if you change the variable used to specify the interval this will have no effect on the internal table: that value has been read when you called setInterval and it's now stored.
To randomize the callback time give your function a name and just use setTimeout instead of setInterval:
function MyCallback() {
...
setTimeout(myCallback, new_delay);
}
setTimeout(myCallback, first_delay);
with this approach at each call you can decide a different delay before next call.
You can't change the value of randomTime2 inside the function as it's pass by value, not reference.
setInterval(someFunction, someNumberValue)
This line of code will call someFunction every someNumberValue-miliseconds. The value is not updated dynamically.
There's lots of ways you could make this work, but I suggest simply using setTimeout and making the end of someFunction call it again. For instance:
//psudo-code, might not actually run, just showing you the general idea.
var someFunction = function(){
console.log("Whatever.");
}
var repeatFunction = function(){
someFunction()
var timeoutID = window.setTimeout(repeatFunction, Math.random()*10000);
}
repeatFunction(); //Starts the loop.

Categories