[英]SetTimeout not working in chrome snippets
I'm writing a code snippet in google chrome to aggregate some data.我正在谷歌浏览器中编写一个代码片段来聚合一些数据。
For some reason my timeout isn't working, here's a very simplified vers...由于某种原因,我的超时不起作用,这是一个非常简化的版本......
let element= document.querySelector(".element");
let link = element.querySelector("a");
link.click();
setTimeout(() => {
console.log("waited");
},500);
console.log("waiting");
My output:我的 output:
waiting
undefined
Navigated to http://127.0.0.1/page.html
My expected output would be:我预期的 output 将是:
undefined
Navigated to http://127.0.0.1/page.html
waiting
waited
It's also strange to me that the output would be reversed as well.我也很奇怪 output 也会被反转。
Any help would be appreciated thanks!任何帮助将不胜感激谢谢!
After link.click()
, it takes a long time to really navigate the page.在
link.click()
之后,真正浏览页面需要很长时间。 Due to asynchronous nature of Javascript, following lines of code will be executed until the real navigation takes place.由于 Javascript 的异步特性,将执行以下代码行,直到真正的导航发生。 So,
所以,
console.log("waiting");
will take place.将会发生。 But
但
setTimeout(() => {
console.log("waited");
}, 500);
will not take place because the real navigation will occur before 500ms.不会发生,因为真正的导航将在 500 毫秒之前发生。
After the real navigation, your codes will be gone unless it takes in place.在真正的导航之后,除非它到位,否则您的代码将消失。
document.body.innerHTML = '' +
'<div class="element">'+
' <a href="#"></a>' +
'</div>';
let element= document.querySelector(".element");
let link = element.querySelector("a");
link.click();
setTimeout(() => {
console.log("waited");
}, 500);
console.log("waiting");
The log of this snippet is:这个片段的日志是:
waiting
undefined
waited
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.