我需要等待5秒才能运行第二行:
function waitnext() {
setTimeout('', 5000);
alert('waited');
}

然而,它似乎在运行该功能时立即打开警报。知道如何解决这个问题吗?感谢
答案 0 :(得分:0)
function waitnext() {
setTimeout( function(){
alert('waited');
}, 5000);
}
waitnext();
你的语法错了。在这里,您可以使用文档 https://www.w3schools.com/jsref/met_win_settimeout.asp
答案 1 :(得分:0)
作为setTimeout
function waitnext() {
setTimeout(function() {
alert('waited'); // runs after 5000ms
}, 5000);
}
答案 2 :(得分:0)
setTimeout
在经过指定的毫秒数后评估回调函数。
使用ES6的解决方案。
let waitnext = () => {
setTimeout(() => {
// callback
alert('waited');
}, 5000);
}
waitnext();

或使用ES5:
'use strict';
var waitnext = function waitnext() {
setTimeout(function () {
// callback
alert('waited');
}, 5000);
};
waitnext();

答案 3 :(得分:0)
function waitnext(){
setTimeout(function(){
alert('waited');
}, 5000);
试试这个
答案 4 :(得分:-1)
一些样品......
var myAlarm = e => console.log(e);
var myStop = () => console.log('stop');
var wait = (delay, callback) => setTimeout(callback, delay);
wait(2000, () => myAlarm("finished after 2 seconds"));
wait(3000, myStop);
// the following line don´t work ...
// the function was executed immediately
wait(4000, myAlarm('cheesecake'));
//use setTimeout
setTimeout(myStop, 1000);
// the following line don´t work ...
// the function was executed immediately
setTimeout(myAlarm('cheesecake'),3000);
// this works
setTimeout(() => myAlarm('cheesecake'),3000);