open函數內部不斷判斷是否讀取就緒,就緒後調用回調函數。
<script>
file=[]
a={}
a.txt='wait for long'
a.js='i am js file'
function sleep(delay) {
var start = (new Date()).getTime();
while ((new Date()).getTime() - start < delay) {
continue;
}
}
setTimeout(
function(){
console.log('i am not ready');
sleep(2000);
console.log('i am ready');
ready=true
}
)
Object.prototype.open=function(file,callback){
setInterval(()=>{
if(ready){
callback(file)
ready=false
}
},0)
return this
}
Object.prototype.on=function(event,callback){
this[event](callback)
}
file.open('a.txt',result=>console.log(eval(result)))
console.log('i am main thread')
//file.open('a.js',result=>console.log(eval(result)))
</script>