作者:oko123 | 来源:互联网 | 2022-12-07 03:10
setTimeout()
很想知道是否会异步启动,我尝试了以下测试脚本:
function timedText() {
var x = document.getElementById("txt");
setTimeout(function() {
x.value = "1 second"
}, 1000);
setTimeout(function() {
x.value = "2 seconds"
}, 2000);
setTimeout(function() {
x.value = "3 seconds"
}, 3000);
while (true) {}
}
Click on the button below. The input field will tell you when two, four, and six seconds have passed.
果然,单击该按钮会导致浏览器挂起.
这告诉我,setTimeout()
并没有一个单独的线程运行.
但在最近的一次采访中,采访者提出了另外的建议......这是否意味着setTimeout()
依赖于浏览器/实现?
1> t.niese..:
Javascript不是多线程的.好吧,WebWorkers运行在不同的线程中,但这并不是真正的多线程,更像是多个进程,它们之间相互通信.
因此,while (true) {}
将阻止js上下文,因为它是一个无限循环.
该setTimeout
会注册后的执行的功能.但是在任何时候代码都不会为相同的上下文并行运行.
A while (true)
本身不一定会创建阻塞循环:
async function sleep(time) {
return new Promise((resolve, _) => setTimeout(resolve, time))
}
async function test(val) {
while (true) {
console.log('in while loop ' + val)
await sleep(1000)
}
}
test('foo')
test('bar')