Javascript 以js间隔打开和关闭网站
我需要建立一个程序,打开一个网站,等待约5秒,然后关闭网站,打开一个不同的网站,它需要循环约5次。网站的URL会像我的代码一样改变。我只是不知道如何使用整个计时器代码。我的代码Javascript 以js间隔打开和关闭网站,javascript,for-loop,timer,settimeout,window.open,Javascript,For Loop,Timer,Settimeout,Window.open,我需要建立一个程序,打开一个网站,等待约5秒,然后关闭网站,打开一个不同的网站,它需要循环约5次。网站的URL会像我的代码一样改变。我只是不知道如何使用整个计时器代码。我的代码 <script> var x = Math.floor(Math.random() * 20) + 1; var y = Math.floor(Math.random() * 28) + 1; for (i = 0; i < 5; i++) { var wnd = window.o
<script>
var x = Math.floor(Math.random() * 20) + 1;
var y = Math.floor(Math.random() * 28) + 1;
for (i = 0; i < 5; i++) {
var wnd = window.open("http://www.random.com/x=" + x + "y=" + y);
setTimeout(function() {
wnd.close();
}, 5000);
};
</script>
var x=数学地板(数学随机()*20)+1;
var y=Math.floor(Math.random()*28)+1;
对于(i=0;i<5;i++){
var wnd=窗口打开(“http://www.random.com/x=“+x+”y=“+y”);
setTimeout(函数(){
wnd.close();
}, 5000);
};
您必须将代码更改为:
var x = Math.floor(Math.random() * 20) + 1;
var y = Math.floor(Math.random() * 28) + 1;
var timesRun = 0;
var interval = setInterval(function(){
timesRun += 1;
if(timesRun === 5){
clearInterval(interval);
}
var wnd = window.open("http://www.random.com/x=" + x + "y=" + y);
setTimeout(function() {
wnd.close();
}, 5000);
}, 5000);
您的代码只需打开5个窗口,然后在5秒钟后逐个关闭它们。此代码应该执行您想要的操作您可能需要等待一个窗口关闭以打开另一个窗口!代码将如下所示:
function openURL(counter, max) {
var x = Math.floor(Math.random() * 20) + 1;
var y = Math.floor(Math.random() * 28) + 1;
var url = "http://www.random.com/?x=" + x + "y=" + y;
if(counter <= max) {
var wnd = window.open(url);
setTimeout(function() {
wnd.close();
openURL(++counter, max);
}, 5000);
}
}
openURL(1, 5);
函数openURL(计数器,最大值){
var x=数学地板(数学随机()*20)+1;
var y=Math.floor(Math.random()*28)+1;
变量url=”http://www.random.com/?x=“+x+”y=“+y;
如果(计数器)我怎样才能使x和y永远不重复?有很多不同的答案。这个答案应该能解决你的问题