Created
August 19, 2018 16:50
-
-
Save spacemeowx2/cc9bdbb19d30518bcba3615bd2ffc74f to your computer and use it in GitHub Desktop.
test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
((async () => { | |
const sleep = ms => new Promise(r => setTimeout(r, ms)) | |
class IdleUnload { | |
/** | |
* @param obj Unloadable 对象 | |
* @param idleTime 超时时间 单位为秒 | |
*/ | |
constructor(obj, idleTime) { | |
this.obj = obj; | |
this.loaded = false; | |
this.task = Promise.resolve(); | |
this.running = 0; | |
this.idleTime = idleTime * 1000; | |
} | |
async execute(...args) { | |
if (this.timeoutId !== undefined) { | |
window.clearTimeout(this.timeoutId); | |
} | |
await this.doLoad(); | |
try { | |
this.running++; | |
return await this.obj.execute(...args); | |
} | |
finally { | |
this.running--; | |
this.afterRun(); | |
} | |
} | |
getFunc() { | |
return (...args) => this.execute(...args); | |
} | |
afterRun() { | |
if (this.running === 0) { | |
if (this.timeoutId !== undefined) { | |
window.clearTimeout(this.timeoutId); | |
} | |
this.timeoutId = window.setTimeout(() => this.doUnload(), this.idleTime); | |
} | |
} | |
async doLoad() { | |
await this.append(async () => { | |
if (this.loaded === false) { | |
await this.obj.load(); | |
this.loaded = true; | |
} | |
}); | |
} | |
async doUnload() { | |
await this.append(async () => { | |
if (this.loaded === true) { | |
await this.obj.unload(); | |
this.loaded = false; | |
} | |
}); | |
} | |
async append(fac) { | |
this.task = this.task.then(fac); | |
await this.task; | |
} | |
} | |
function idleUnload(obj, idleTime) { | |
return (new IdleUnload(obj, idleTime)).getFunc(); | |
} | |
let times = 0 | |
const f = idleUnload({ | |
async load () { | |
console.log('loading') | |
await sleep(1000) | |
this.loaded = true | |
console.log('load done') | |
}, | |
async unload () { | |
console.log('unloading') | |
await sleep(1000) | |
this.loaded = false | |
console.log('unload done') | |
}, | |
async execute () { | |
const id = ++times | |
console.log('executing', this.loaded, id) | |
await sleep(500) | |
console.log('execute done', this.loaded, id) | |
} | |
}, 1) | |
await f() | |
await f() | |
await sleep(2000) | |
f() | |
await sleep(200) | |
f() | |
await sleep(200) | |
f() | |
await sleep(200) | |
f() | |
await sleep(200) | |
f() | |
await sleep(200) | |
f() | |
await sleep(200) | |
f() | |
await sleep(200) | |
f() | |
await sleep(200) | |
f() | |
await sleep(200) | |
f() | |
await sleep(200) | |
f() | |
})(), undefined) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment