0

My program opens 2-7 webpages after manipulating a portion of the url for each iteration (increments the date value in the url). I want my program to pause before it opens the next url. Ex: Opens URL 1 -> wait 1.5 secs -> Open URL 2...etc

My javascript function looks something like this:

function submitClicked(){
save current date in URL as variable
loop(4 times){
window.open(urlString); //open the initial URL
var newDate = getNextDay(date);
urlString.replace(date, newDate); (ex: if 2016-12-31 then replace it in URL with with 2017-01-01)
**wait 1.5 seconds**
}

function getNextDay(date){
...
return result (String value)
}

So basically, I want it to pause 1.5 seconds at the end of each iteration of the loop. I made the same program in Java and simply used Thread.sleep(1500);

btrballin
  • 1,276
  • 3
  • 23
  • 35
  • Possible duplicate of [What do I do if I want a JavaScript version of sleep()?](http://stackoverflow.com/questions/951021/what-do-i-do-if-i-want-a-javascript-version-of-sleep) – Sam Segers Apr 26 '16 at 23:23

1 Answers1

2

You should never attempt to block a thread execution in JavaScript, as that will cause the browser to feel stuttery and generally provide a very bad experience for your users. You can refactor using setInterval to prevent this.

arr = ['http://site1', 'http://site2', 'http://site3'];
timer = null;

function instantiateTimer(){
  timer = setInterval(openPage, 1000); // 1 second
}

function openPage(){
  if(arr.length > 0){
    page = arr.pop();
    window.open(page) // some browsers may block this as a pop-up!
  }else{
    clearInterval(timer);
  }
}
Jacob See
  • 740
  • 6
  • 17