Javascript 函数在3秒后返回
所以我有一个我想运行的函数:Javascript 函数在3秒后返回,javascript,asynchronous,callback,promise,settimeout,Javascript,Asynchronous,Callback,Promise,Settimeout,所以我有一个我想运行的函数: const normal = () => { return 'working } 我可以记录它的输出,并且工作正常: console.log(normal()) // does output: 'working' 现在我想运行一个函数delayed,它与normal完全相同,只是需要3秒钟才能返回 我希望能够记录此函数调用,但仅在3秒钟后,我就可以理解目前正在记录未定义的,并且有一种可能的感觉。无论如何,我希望发生以下情况,函数挂起3秒钟,然后返回数据
const normal = () => {
return 'working
}
我可以记录它的输出,并且工作正常:
console.log(normal()) // does output: 'working'
现在我想运行一个函数delayed
,它与normal
完全相同,只是需要3秒钟才能返回
我希望能够记录此函数调用,但仅在3秒钟后,我就可以理解目前正在记录未定义的
,并且有一种可能的感觉。无论如何,我希望发生以下情况,函数挂起3秒钟,然后返回数据:
console.log(delayed()) // should output: 'working'
我的尝试:
const toReturn = () => {
return 'working'
}
const runner = (cb) => {
setTimeout(cb, 1000)
}
export const delayed = () => {
return runner(toReturn)
}
console.log(delayed()) // currently outputting: undefined
未定义是因为我没有从runner返回任何内容,如果我在runner中返回setTimout…,我只得到整个setTimout函数,这是非常无用的
我知道您可以在回调3秒钟后简单地登录,但我想在您调用
控制台时记录setTimeout返回的内容。log
(或其他任何内容)然后它将执行该操作。JS不像某些语言那样暂停代码执行
如果要延迟console.log
,则需要延迟对console.log
的实际调用,而不是延迟正在记录的值的返回
最简单的方法如下:
function delayedLog(seconds)
{
setTimeout(function(){
var val = getSomething(); // <- pretend this returns "later"
console.log(val); // <- after 3 seconds logs "later"
}, seconds*1000);
}
console.log('now');
delayedLog(3);
函数延迟日志(秒)
{
setTimeout(函数(){
var val=getSomething();//您的意思是,锁定用户的浏览器3秒钟?当然可以!但不要期望任何正面反馈。这会使系统无响应并破坏用户的工作。