簡體   English   中英

定期運行JavaScript函數

[英]Run JavaScript function at regular time interval

我目前正在建立一個網站來托管軟件。 我想要添加到項目頁面的是一個循環播放屏幕截圖的幻燈片,大約每5秒更改一次圖像。 有什么辦法可以僅使用JavaScript在一定時間間隔內觸發腳本嗎? ..或者我將不得不采用替代方法來實現所需的功能。 在此先感謝您的幫助!

setInterval

function doSomething() {
    alert('This pops up every 5 seconds and is annoying!');
}

setInterval(doSomething, 5000); // Time in milliseconds

每隔n毫秒將您要重復調用的函數傳遞給它。 (順便說一下, setTimeout將調用帶有超時的函數。)

如果您想停止計時器,請保留setInterval的返回值並將其傳遞給clearInterval

您需要setInterval函數。

setInterval(function() {
  // This will be executed every 5 seconds
}, 5000); // 5000 milliseconds

基本參考: http : //www.w3schools.com/jsref/met_win_setinterval.asp (請忽略對“ lang”參數的參考)

更深入的參考: https : //developer.mozilla.org/en-US/docs/Web/API/window.setInterval

您可以使用window.setInterval

用法示例:

window.setInterval(function () {
    console.log("foo");
}, 3000);

它會更改div中的日期時間,並且1秒后會頻繁更改時間。

    setInterval(function(){
      var date=new Date();
      $('.class').html(date);
    },1000);
<script>
var intervalVariable=setInterval(function(){
   //Your operation goes Here
  },1000); // executes every 1000 milliseconds(i.e 1 sec)

function stopTimer()
{
   clearInterval(intervalVariable);
}
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM