需要让函数在返回字符串之前等待 4 秒,但运气不佳。基本上这就是我想要做的:
function myFunction(){
var str = '';
// DO SOMEHITNG HERE so when it's done the finally return "I'm done"
return "I'm done";
}
这就是我目前所拥有的(我缺少什么),但我也没有其他方法可以做到这一点。提前致谢!
function myFunction(){
var counter = 0;
var execute = setInterval(print, 1000);
function print(){
document.write("Counting" + counter + "<br/>");
++counter;
if(counter < 5){
clearInterval(execute);
str = "I'm done";
}
}
return str; // Here I want to return "I'm done"
}
最佳答案
你不能像你想要的那样延迟函数的返回,但你可以返回一个 Promise。对于这样的情况,你需要使用 sime king 的异步函数:
function myFunction() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve("I'm done");
}, 5000)
}
}
// Now when you use your function, you need to get the results from a then method:
let someVariable;
myFunction().then(function(output) {
console.log(output); // I'm done
someVariable = output;
}
console.log(someVariable); // undefined
请记住,异步函数始终是异步的。这就是为什么最后一个控制台日志将输出 undefined
。
关于javascript - 如何让函数在返回前等待 4 秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58642603/