如何让浏览器控制台在 javascript 中等待
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30789142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a browser console wait in a javascript
提问by Daniel M?ller
I'm trying to make a script that clicks on a page button, waits X seconds (for the result of the click to take place), and then continues.
我正在尝试制作一个点击页面按钮的脚本,等待 X 秒(点击结果发生),然后继续。
How can I do that? (only the wait part)
我怎样才能做到这一点?(只有等待部分)
回答by Shushanth Pallegar
using setTimeout, which executes only once after the delay provided
使用 setTimeout,它在提供的延迟后只执行一次
setTimeout(function(){
console.log('gets printed only once after 3 seconds')
//logic
},3000);
using setInterval , which executes repeatedly after the delay provided
使用 setInterval ,它在提供的延迟后重复执行
setInterval(function(){
console.log('get printed on every 3 second ')
},3000);
clearTimeout
and clearInterval
is used to clear them up !!!
clearTimeout
并clearInterval
用于清除它们!!!
回答by Luke Shimkus
You want to use setTimeout()
which executes a code snippet after a specified delay.:
您想使用setTimeout()
which 在指定延迟后执行代码片段。:
var timeoutID;
function delayedAlert() {
timeoutID = setTimeout(slowAlert, 2000);
}
function slowAlert() {
alert("That was really slow!");
}
function clearAlert() {
clearTimeout(timeoutID);
}
<p>Live Example</p>
<button onclick="delayedAlert();">Show an alert box after two seconds</button>
<p></p>
<button onclick="clearAlert();">Cancel alert before it happens</button>
Or you can use setInterval()
which calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function:
或者您可以使用setInterval()
which 调用函数或重复执行代码片段,在每次调用该函数之间具有固定的时间延迟:
function KeepSayingHello(){
setInterval(function () {alert("Hello")}, 3000);
}
<button onclick="KeepSayingHello()">Click me to keep saying hello every 3 seconds</button>