打开10张Unsplash随机图时setTimeout延迟失效问题求助
问题根因
- 相同URL触发缓存复用:Unsplash随机图接口对完全一致的请求URL会返回相同图片,同时浏览器会对相同URL的GET请求启用缓存,因此10次请求得到的是同一张图。
setTimeout调用错误:- 直接传入
window.open("xxx")时,括号会立即执行开窗逻辑,返回的窗口对象被传给setTimeout,延迟完全不生效 - 循环中所有定时器都设置为5秒后触发,会导致5秒后一次性打开10个标签页,仍然是同URL请求返回同一张图
- 直接传入
解决方案
最优方案(无需延迟,直接生成不同图片)
给每个请求的URL添加随机查询参数,保证每个请求URL唯一,跳过缓存即可拿到不同的随机图,代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> body{margin:0px;color:#252430;background-color:#fff} p{margin-top: 10em; font-size: 2em;} </style> <script> function openitall(){ for(let i=1;i<=10;i++){ // 追加随机参数保证URL唯一 const targetUrl = `https://source.unsplash.com/random/1920x1080?t=${Date.now()}_${i}` window.open(targetUrl,"_blank"); } } </script> </head> <body onload="openitall()"> <p align="center">我是一个可在新标签页打开10张随机图片的页面</p> </body> </html>
带延迟的兼容方案(避免浏览器弹窗拦截)
如果浏览器拦截了自动触发的批量弹窗,可以采用间隔延迟打开的方式,同时保留随机参数保证图片不同:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> body{margin:0px;color:#252430;background-color:#fff} p{margin-top: 10em; font-size: 2em;} </style> <script> function openitall(){ for(let i=1;i<=10;i++){ const targetUrl = `https://source.unsplash.com/random/1920x1080?t=${Date.now()}_${i}` // 每个标签页间隔1秒打开,降低弹窗拦截概率 setTimeout(() => { window.open(targetUrl,"_blank"); }, i * 1000) } } </script> </head> <body onload="openitall()"> <p align="center">我是一个可在新标签页打开10张随机图片的页面</p> </body> </html>
如果仍然被拦截,可以将openitall绑定到按钮的点击事件上,由用户主动触发的弹窗不会被浏览器拦截。
内容的提问来源于stack exchange,提问作者Jane N.
相关产品推荐
相关产品推荐

