简体   繁体   English

如何在JavaScript中暂停执行?

[英]How to pause execution in javascript?

My program opens 2-7 webpages after manipulating a portion of the url for each iteration (increments the date value in the url). 我的程序在为每次迭代处理了一部分网址(增加网址中的日期值)后,会打开2-7个网页。 I want my program to pause before it opens the next url. 我希望程序在打开下一个URL之前暂停。 Ex: Opens URL 1 -> wait 1.5 secs -> Open URL 2...etc 例如:打开URL 1->等待1.5秒->打开URL 2 ... etc

My javascript function looks something like this: 我的javascript函数如下所示:

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. 因此,基本上,我希望它在循环的每次迭代结束时暂停1.5秒。 I made the same program in Java and simply used Thread.sleep(1500); 我用Java Thread.sleep(1500);了相同的程序,只使用了Thread.sleep(1500);

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. 您永远不要尝试在JavaScript中阻止线程执行,因为这将导致浏览器感觉不稳定,并且通常会给用户带来非常糟糕的体验。 You can refactor using setInterval to prevent this. 您可以使用setInterval进行重构以防止这种情况。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM