我有一个返回回调的函数。其执行时间可能会有所不同。有没有办法在上面设置超时回调?或者终止函数并重新编写代码?
这是一场暂停游戏
以下是使用setTimeout
和Promise
的示例
function executeWithin(targetFn, timeout) {
let invoked = false;
return new Promise((resolve) => {
targetFn().then(resolve)
setTimeout(() => {
resolve('timed out')
}, timeout)
})
}
executeWithin(
// function that takes 1sec to complete
() => new Promise((resolve) => {
setTimeout(() => {
resolve('lazy fn resolved!')
}, 1000)
}),
2000 // must invoke callback within 2sec
).then(console.log)
// => lazy function is finally done!
executeWithin(
// function that takes 3s to complete
() => new Promise((resolve) => {
setTimeout(() => {
resolve()
}, 3000)
}),
2000 // must invoke callback within 2sec
).then(console.log)
// => timed out