循环中的setTimeout同时执行

setTimeout in a loop execute all at the same time

我想每 3 秒打开一个 link。我正在使用 setTimeout 函数,但它不起作用。所有 link 将被打开一次。

for(var i=0; i < url.length-1; i++) {
  setTimeout(function(){
    linkaddress=url[i];
    window.open(linkaddress);
  }, 3000);
}

使用 "let" 而不是 "var" 进行块级范围界定,然后将您的时间乘以 i 变量 (more info)。代码:

 var url = ["https://domain1.com","https://www.domain2.com"],
     timeout = 3; // Time in second

 for(let i=1; i <= url.length; i++){
   setTimeout(function(){
     linkaddress=url[i-1];
     window.open(linkaddress);
   }, i * timeout * 1000);
 }

编辑:请注意,此代码使用 EcmaScript 6 功能

使用 setInterval 代替

url = ['a', 'b', 'c'];

var i = 0;
var interval = setInterval(function() {
  if (i <= url.length - 1) {
    ///linkaddress = url[i];
    //window.open(linkaddress);
    console.log(url[i]);
    i++;
  } else {
    clearInterval(interval);
  }
}, 3000);