JQuery,如何每5秒调用一个函数。

我正在寻找一种方法来自动更改幻灯片中的图像。

如果可能的话,我宁愿不安装任何其他第三方插件。


你不需要jquery,在纯javascript中,以下将工作:

var intervalId = window.setInterval(function(){
  // call your function here
}, 5000);

要停止循环,您可以使用:

clearInterval(intervalId) 

你可以使用setInterval在页面上注册一个间隔,即:

setInterval(function(){ 
    //code goes here that will be run every 5 seconds.    
}, 5000);

setInterval和setTimeout都可以为您工作(正如@Doug Neiner和@John Boker所写的,现在都指向setInterval)。 这里有更多关于两者的解释,看看哪个最适合你,以及如何阻止它们。

关于第一个答案,有个小提示。如果函数已经定义,请引用该函数,但不要调用它!!所以不要在函数名后面加括号。就像:

my_function(){};
setInterval(my_function,10000);

上面提到的函数无论在之前的调用中是否已经完成,都会执行,这个函数在执行完成后每x秒运行一次

// IIFE
(function runForever(){
  // Do something here
  setTimeout(runForever, 5000)
})()

// Regular function with arguments
function someFunction(file, directory){
  // Do something here
  setTimeout(someFunction, 5000, file, directory)
  // YES, setTimeout passes any extra args to
  // function being called
}

一个订阅setInterval()并使用clearInterval()来停止永久循环的好例子:

function everyTime() {
    console.log('each 1 second...');
}

var myInterval = setInterval(everyTime, 1000);

调用这一行来停止循环:

 clearInterval(myInterval);

你可以用window。setInterval和time必须以毫秒为单位定义,在下面的情况下,函数将在每一秒(1000毫秒)后调用一次

<script>
  var time = 3670;
window.setInterval(function(){

  // Time calculations for days, hours, minutes and seconds
    var h = Math.floor(time / 3600);
    var m = Math.floor(time % 3600 / 60);
    var s = Math.floor(time % 3600 % 60);

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML =  h + "h "
  + m + "m " + s + "s ";

  // If the count down is finished, write some text 
  if (time < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }

  time--;
}, 1000);


</script>