<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>开启js多线程</title>
</head>
<body>
<button id="button">运行</button>
<script>
document.getElementById('button').onclick = function () {
console.log('点击');
let url = scriptToUrl(sleep);
console.log(url);
newWork(url);
test("我应该被阻塞的");
};
function test(msg) {
console.log(arguments);
console.log(msg);
}
//使用for循环实现阻塞
function sleep(d) {
for (var t = Date.now(); Date.now() - t <= 3000;);
console.log("另一个线程循环结束");
}
function newWork(url) {
return myWorker = new Worker(url);
}
// js转bolb url链接
function scriptToUrl(script) {
return URL.createObjectURL(new Blob([`(${script.toString()})()`]));
}
test(123)
</script>
</body>
</html>