如何每小时自动调用javascript函数

How to automatically call javascript function every hour?

本文关键字:调用 javascript 函数 每小时      更新时间:2023-09-26

我有一个javascript函数,它从URL获取JSON对象,我想每小时用最新数据刷新一次JSON对象。

我假设这样做的方法是调用javascript函数,该函数每小时从URL获取JSON对象。

然而,我不知道如何将函数设置为每小时自动重新运行一次,有人能解释一下是如何做到的吗?

感谢

function doSomething()
{
    alert('Test');
}

setInterval(doSomething, 60*60*1000);

您可以通过设置一个间隔来重新调用您的函数:

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

您可以尝试:

setInterval(function(){alert("Hello")},3600000);

其中3600000是以毫秒为单位的时间间隔。

使用setInterval,如下所示:-

语法

setInterval(function,milliseconds,lang)

参数值

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 

返回值

一个整数,其中包含已设置的计时器的ID值。将此值与clearInterval()方法一起使用可以取消计时器。

示例

function test() 
{
     ////Your code
}
setInterval(function(){test()}, 60 * 60 *1000); //// 60 minutes = 3600 seconds = 3600000 miliseconds 

有关更多详细信息:-

http://www.w3schools.com/jsref/met_win_setinterval.asp