JavaScript-自测题18

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
请问点击<button id="test"></button>会有什么反应?为什么?能解决吗?

$("#test").click(function(argument){
console.log(1); 控制台打印1
});

setTimeout(function(){
console.log(2); // 2 立即执行控制台打印2
},0);

while(true){
console.log(Math.random()); //返回随机数
}

解析:
优先执行while 无限循环 后面无法执行

技术点:在JS单线程的时候如何模拟多线程操作

解决:
1. 让出CPU时间,setTimeout延迟执行
2. web worker 独立线程开放(无法执行DOM操作,只允许纯计算)
3. 并发库Concurrent.Thread.js 实现原理时间切片