在浏览器控制台中执行时暂停Javascript

时间:2018-11-20 14:44:14

标签: javascript google-chrome delay sleep

我需要在Chrome控制台中执行Javascript,但要延迟一些时间。该怎么办?

我需要这个的原因是,焦点从网页(或网页的某个元素)更改后会立即重绘。因此,我想延迟几秒钟来启动在控制台中执行的脚本,以便将焦点更改为正在使用的页面上正确的元素。

编辑1:Dinesh Padiyan。

对我不起作用,屏幕截图:

enter image description here

3 个答案:

答案 0 :(得分:4)

您可以像这样扩展console对象,然后使用自定义logLater方法。

enter image description here

console.logLater = (message, delay) => setTimeout(function() {
  console.log(message);
}, delay);

console.log('I will be printed immediately');

console.logLater('I will be printed after 3 seconds', 3000);

答案 1 :(得分:1)

function delay (ms){   return new Promise(resolve => setTimeout(resolve, s));  }

“异步”工作演示: http://zarsoft.info/software/_Test/pause_javascript/index.html

答案 2 :(得分:0)

如果出于调试目的需要延迟,则需要在代码中添加debugger;条语句。添加调试器并打开开发人员工具后,脚本执行将在您的debugger;语句处暂停,您可以在开发人员工具中检查代码。

console.log('I will execute');
debugger; // execution will pause at this line
console.log("I won't execute until you say so");

如果您需要因网站行为而延迟执行,可以使用setTimeout()来延迟调用。

console.log('I will be printed immediately');
setTimeout(function() {
  console.log('I will be printed after 5s');
}, 5000); // 3s delay

相关问题