I have a javascript function that gets a JSON object from a URL and I want to refresh the JSON object every hour with up to date data.
I am assuming the way to do this is to recall the javascript function that gets the JSON object from a URL every hour.
However I do not know how to set a function to automatically rerun every hour, could someone explain how this is done?
Thank you
I have a javascript function that gets a JSON object from a URL and I want to refresh the JSON object every hour with up to date data.
I am assuming the way to do this is to recall the javascript function that gets the JSON object from a URL every hour.
However I do not know how to set a function to automatically rerun every hour, could someone explain how this is done?
Thank you
Share Improve this question asked Oct 2, 2014 at 11:43 Cu1tureCu1ture 1,2831 gold badge15 silver badges30 bronze badges 8-
2
client side? you can use
setInterval
, this requires your page to be open and stay opened all the time though.. – BeNdErR Commented Oct 2, 2014 at 11:45 - 4 read up on setinterval - but who has a web page open for an hour? – Ed Heal Commented Oct 2, 2014 at 11:45
- 1 you could probably use a cron job look at this URL stackoverflow./questions/4695629/… – chaos505 Commented Oct 2, 2014 at 11:47
- Presuming the AJAX contacts a server side language (PHP or whatever), store the time of the last refresh in a database. Then, check that an hour has passed against the stored last update time before requesting the JSON object. – ggdx Commented Oct 2, 2014 at 11:48
- Could everyone writing an answer at least get the number of bloody milliseconds right? Sheesh. – Andy Commented Oct 2, 2014 at 11:49
4 Answers
Reset to default 6function doSomething()
{
alert('Test');
}
setInterval(doSomething, 60*60*1000);
You could re-call your function with setting an interval:
<script type="text/javascript">
function getJSONObjectFromURL(){
// do stuff
}
//set interval in milliseconds and call function again
//1h = 60m = 3600s = 3600000ms
var timeoutID = window.setInterval(getJSONObjectFromURL, 3600000);
</script>
You may try:
setInterval(function(){alert("Hello")},3600000);
Where 3600000 is the time interval in miliseconds.
Go with setInterval
as shown below :-
Syntax
setInterval(function,milliseconds,lang)
Parameter Values
Parameter Description
function Required. The function that will be executed
milliseconds Required. The intervals (in milliseconds) on how often to execute the code
lang Optional. JScript | VBScript | JavaScript
Return Value
An integer with the ID value of the timer that is set. Use this value with the clearInterval() method to cancel the timer.
Example
function test()
{
////Your code
}
setInterval(function(){test()}, 60 * 60 *1000); //// 60 minutes = 3600 seconds = 3600000 miliseconds
For more details :-
http://www.w3schools./jsref/met_win_setinterval.asp