0

I want to open a link every 3 seconds. I am using the setTimeout function, but it doesn't work. All links will be opened once.

for(var i=0; i < url.length-1; i++) {
  setTimeout(function(){
    linkaddress=url[i];
    window.open(linkaddress);
  }, 3000);
}
Ivar
  • 6,138
  • 12
  • 49
  • 61
Eyte adm
  • 5
  • 2

2 Answers2

1

Use "let" instead of "var" for block level scoping, and then multiply your time by i variable (more info). Code:

 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);
 }

EDIT: Note that this code uses EcmaScript 6 features

jacqbus
  • 457
  • 3
  • 13
1

Use setInterval instead

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);
ACD
  • 1,431
  • 1
  • 8
  • 24