题目1:设计LazyMan
要求设计 LazyMan 类,实现以下功能:
LazyMan('Tony');
// Hi I am Tony
LazyMan('Tony').sleep(10).eat('lunch');
// Hi I am Tony
// 等待了10秒...
// I am eating lunch
LazyMan('Tony').eat('lunch').sleep(10).eat('dinner');
// Hi I am Tony
// I am eating lunch
// 等待了10秒...
// I am eating diner
LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food');
// Hi I am Tony
// 等待了5秒...
// I am eating lunch
// I am eating dinner
// 等待了10秒...
// I am eating junk food
题解1
class LazyManClass {
constructor(name) {
this.taskList = [];
this.name = name;
console.log(`Hi I am ${name}`);
setTimeout(() => {
this.next();
}, 0)
}
sleep(time) {
var _this = this;
var fn = (function(time) {
return function() {
setTimeout(() => {
console.log(`等待了${time}秒...`);
_this.next();
}, time * 1000)
}
})(time);
this.taskList.push(fn);
return this;
}
eat(data) {
var _this = this;
var fn = (function(data) {
return function() {
console.log(`I am eating ${data}`);
_this.next();
}
})(data);
this.taskList.push(fn);
return this;
}
sleepFirst(time) {
var _this = this;
var fn = (function(time) {
return function() {
setTimeout(() => {
console.log(`等待了${time}秒...`);
_this.next();
}, time * 1000)
}
})(time);
this.taskList.unshift(fn);
return this;
}
next() {
var fn = this.taskList.shift();
fn && fn();
}
}
var LazyMan = function(name) {
return new LazyManClass(name);
};
// 测试
LazyMan('Tony');
LazyMan('Tony').sleep(10).eat('lunch');
LazyMan('Tony').eat('lunch').sleep(10).eat('dinner');
LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food');
题目2:红绿灯
题目要求,设计一个红绿灯,红灯3秒一次,黄灯2秒一次,绿灯一秒一次,循环亮起
题解2
function sleep(time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, time*1000)
})
};
async function light(name, time) {
await console.log(`${name}灯亮`);
await sleep(time);
}
async function step() {
while(true) {
await light('红', 3);
await light('黄', 2)
await light('绿', 1)
}
};
step();
题目3
实现一个红绿灯,把一个圆形 div 按照绿色 3 秒,黄色 1 秒,红色 2 秒循环改变背景色。
题解3
function sleep (fn, time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
fn && fn();
resolve();
}, time * 1000);
});
}
function changeBGColor(color) {
if (!document.getElementById('light')) {
var light = document.createElement('div');
light.setAttribute('id', 'light');
light.setAttribute('style', 'width: 30px; height: 30px; border-radius: 50%; border: 1px solid #000');
document.body.appendChild(light);
}
document.getElementById('light').style.backgroundColor = color;
}
async function run() {
while (true) {
await sleep(changeBGColor('green'), 3);
await sleep(changeBGColor('yellow'), 1);
await sleep(changeBGColor('red'), 2);
}
}
run();