LazyMan(面试题详解)

思路展示

视频观看 文章观看

面对题目先经过将目标分解为一个个小目标,逐个实现小目标,将程序实现可以运行。重新梳理程序代码,优化整合。

常见运行时间

代码展示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Bin</title>
</head>
<body>
<script type="text/javascript">
function LazyMan(name) {
var api = {
// 在任务表后面添加一个待办,等待*秒后执行下一个事件
sleep: function (second) {
task.push(function () {
setTimeout(function () {
console.log("Wake up after " + second)
next()
},second*1000)
})
return this
},
// 在任务表前面面添加一个待办,等待*秒后执行下一个事件
sleepFirst: function (second) {
task.unshift(function () {
setTimeout(function () {
console.log("Wake up after " + second)
next()
},second*1000)
})
return this
},
// 在任务表后面添加一个待办:吃,然后执行下一个事件
eat: function (what) {
task.push(function () {
console.log("Eat " + what)
next()
})
return this
},
// 在任务表后面添加一个待办:说,然后执行下一个事件
say: function (name) {
task.push(function () {
console.log("Hi, this is " + name)
next()
})
return this
}
}
var task = []
var next = function () {
// 从任务列表中取得第一个
var fn = task.shift()
// 执行
fn && fn.call()
}
api.say(name)
setTimeout(function () {
next()
},0)
return api
}
// LazyMan("Hank")
// LazyMan("Hank").sleep(3).eat("dinner")
// LazyMan("Hank").eat("lunch").eat("dinner")
LazyMan("Hank").sleepFirst(3).eat("dinner")
</script>
<script type="text/javascript">
var _loop = function _loop(i) {
setTimeout(function () {
console.log(i);
},100*i)
}
for (var i = 0; i < 10; i++) {
_loop(i)
}
for (var j = 0; j < 10; j++) {
setTimeout(function () {
console.log(j);
},100*j)
}
var myTeacher = "Mrs. Tysick"
var yourTeacher = myTeacher
console.log(myTeacher)
console.log(yourTeacher)
myTeacher = "Mrs. Goodyear"
console.log(myTeacher)
console.log(yourTeacher)
</script>
</body>
</html>