方法1 setTimeout
function timeoutify(fn, delay) {
var intv = setTimeout(function() {
intv = null;
fn(new Error("Timeout!"));
}, delay);
return function() {
if (intv) {
clearTimeout(intv);
fn.apply(this, arguments);
}
}
}
方法2 promise
function test() {
return new Promise((resolve, reject) => {
setTimeout(function() {
console.log('test')
resolve('test')
}, 3000)
})
}
function timeoutfn() {
return new Promise((resolve, reject) => {
setTimeout(function() {
console.log('timeoutfn')
resolve('timeoutfn')
}, 4000)
})
}
Promise.race([
test(),
timeoutfn()
]).then(res => {
console.log('race end')
}).catch(err => {
console.log('race err')
})