jiefancis / blogs

个人博客,学习笔记(issues)
1 stars 0 forks source link

带取消功能的延迟函数实现 #31

Open jiefancis opened 2 years ago

jiefancis commented 2 years ago
function createPromise() {
    let resolved = null, rejected = null;
    let promise = new Promise((resolve, reject) => {
        resolved = resolve
        rejected = reject
    })
    promise.resolved = resolved
    promise.rejected = rejected
    return promise
}
function delay(time = 1000, promise) {
    let start, timeout = null

    return {
        delay() {
            start = Date.now()
            timeout = setTimeout(promise.rejected, time)
        },
        resolve(value) {
            promise.resolved(value)
        },
        stop() {
            if(Date.now() - start < time) {
                clearTimeout(timeout)
            }
        }
    }
}

function Delay(options) {
    this._promise = createPromise()
    this._delay = delay(options.time, this._promise)
}
Delay.prototype.stop = function() {
    this._delay.stop()
}
Delay.prototype.resolve = function(value) {
    this._delay.resolve(value)
}
Delay.prototype.delay = function() {
    this._delay.delay()
}
Delay.prototype.then = function(resolveFn, rejectFn) {
    this._promise.then(resolveFn, rejectFn)
}
Delay.prototype.catch = function(rejectFn) {
    this._promise.catch(rejectFn)
}
var o = new Delay({time: 3000})
o.then(res => console.log('then', res))
o.catch(err => console.log('catch', err))
o.delay()

setTimeout(() => o.stop(), 2000)