工具函数系列-超时取消事件

方法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

// 使用promise.race 竞速 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')
})