簡體   English   中英

是否可以在Javascript中每10分鍾重復一次循環?

[英]Is it possible to repeat a loop every 10 minutes in Javascript?

我想執行此循環(一首歌曲),然后等待10分鍾,然后它才會重復。

for (i = 0; i < 3; i++) { 

var audio =    document.createElement("");

audio.src = "my_sound.mp3";
audio.play();

};

如果有人可以幫助我,那將是很棒的。

可以很容易地做到這一點:

function play () {
  for (i = 0; i < 3; i++) { 

  var audio =    document.createElement("audio");

  audio.src = "my_sound.mp3";
  audio.play();

  };
}



setInterval(play, 600000);  
//the function name.  do not put () after it as you aren't executing it.  
//600000 is the number of milliseconds in 10 minutes.

play(); //this will execute it immediately the first time if you want.

setInterval

嘗試使用此:

setInterval(function() {
    for (i = 0; i < 3; i++) { 

      var audio = document.createElement("audio");

      audio.src = "my_sound.mp3";
      audio.play();
    } 
}, 600 * 1000);

您可以使用setTimeout()setInterval() ,但是您不能指望它恰好是10分鍾,因為該函數將在事件循環中排隊,並且僅在達到超時時間並且JavaScript運行時處於空閑狀態時才會觸發。

setTimeout()將回調函數作為第一個參數,將一個數字(以毫秒為單位)作為第二個參數。 將該數字視為“等待超時功能的最短時間”。

function go(){
  // Clear the previous timer
  timer = null;

  for (i = 0; i < 3; i++) {     
    var audio =    document.createElement("audio");  
    audio.src = "my_sound.mp3";
    audio.play();
  }

  // Re-run the timer
  timer = setTimeout(go, 600000);
}

var timer = setTimeout(go, 600000);

或者,使用setInterval()

var timer = setInterval(function(){
  for (i = 0; i < 3; i++) {     
    var audio =    document.createElement("audio");  
    audio.src = "my_sound.mp3";
    audio.play();
  } 
}, 600000);

您正在尋找使用setInterval()或setTimeout

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

第一個在X時間執行一次,第二個在X時間過去之后執行,使用哪個取決於您循環的無限性或是否要退出循環,因為可以在執行或使用之前在setTimeout中求值另一個為clearInterval()。

創建一個超時后自動調用的函數,並調用一次

function createAudioElement() {
    for (i = 0; i < 3; i++) { 

        var audio = document.createElement("audio");  
        audio.src = "my_sound.mp3";
        audio.play();
  };

  setTimeout(createAudioElement, 600000);
}

createAudioElement();

確保在document.createElement()指定要創建的元素-在這種情況下為audio ,否則將引發錯誤。

暫無
暫無

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

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