面试题:LazyMan

1,093 阅读1分钟

考点:同异步、原型、原型链、while while:不确定循环次数;阻止主线程;

/*实现一个LazyMan,可以按照以下方式调用:
1) LazyMan(“Hank”)输出:
Hi! This is Hank!

2) LazyMan(“Hank”).sleep(10).eat(“dinner”)输出
Hi! This is Hank!
//等待10秒..
Wake up after 10
Eat dinner~

3) LazyMan(“Hank”).eat(“dinner”).eat(“supper”)输出
Hi This is Hank!
Eat dinner~
Eat supper~

4) LazyMan(“Hank”).sleepFirst(5).eat(“supper”)输出
//等待5秒
Wake up after 5
Hi This is Hank!
Eat supper */

function LazyMan(name) {
	function Man() {
		setTimeout(function () {
			console.log(`Hi! This is ${name}`);
		},0)
	}
	let t=null;
	Man.prototype.sleep=function (time) {
		t=time;
		setTimeout(function () {
			console.log(`Wake up after ${time}`)
		},time*1000);
		return this;
	}
	Man.prototype.eat=function (food) {
		setTimeout(function () {
			console.log(` Eat ${food}~`)
		},t*1000)
		return this;
	}
	Man.prototype.sleepFirst=function (tim) {
		let curTime = new Date();
		while(new Date()-curTime<=tim*1000){
		}
		console.log(`Wake up after ${tim}`)
		return this;
	}
	return new Man();
}