異步讀取文件的原理

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>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章