Javascript 如何在运行下一行代码之前等待 x 秒?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46942255/
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
Javascript How do I wait x seconds before running next line of code?
提问by Abishek Roka
I would like to be able to make something similar to this:
我希望能够做出与此类似的事情:
function testFunction() {
alert("Test");
}
if (x > y) {
wait(z);
testFunction();
}
Thanks!
谢谢!
回答by IAmCoder
Can now nicely be done with promises:
现在可以用 Promise 很好地完成:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
console.log('Taking a break...');
await sleep(2000);
console.log('Two second later');
}
demo();
回答by nocarrier
Please try using the setTimeout function:
请尝试使用 setTimeout 函数:
setTimeout(function(){ alert("Hello"); }, 3000);
From this link:
从这个链接:
https://www.w3schools.com/jsref/met_win_settimeout.asp
https://www.w3schools.com/jsref/met_win_settimeout.asp
So for your specific use case:
因此,对于您的特定用例:
var timeToWait = 3000; // in miliseconds.
function testFunction() {
alert("Test");
}
if (x > y) {
setTimeout(function(){ testFunction(); }, timeToWait);
}
Hope that helps.
希望有帮助。
回答by prgrm
You have to put your code in the callback function you supply to setTimeout:
您必须将代码放在提供给 setTimeout 的回调函数中:
function stateChange(newState) {
setTimeout(function () {
if (newState == -1) {
alert('VIDEO HAS STOPPED');
}
}, 5000);
}
From this question: Javascript - Wait 5 seconds before executing next line
来自这个问题:Javascript - 在执行下一行之前等待 5 秒

