1 回答
TA贡献1772条经验 获得超8个赞
JavaScript确实是一种单线程语言,但支持异步代码。
那是什么意思?
这意味着没有两个代码块会同时运行。在像Java这样的多线程语言中,两个函数可以同时运行,每个函数都在自己的线程上运行。然而,在JavaScript中,即使使用异步代码,所有需要运行的代码都将被放入一个“队列”中,只是代码的顺序最终在“队列”中取决于您的逻辑是否是同步的。
例如:
const work = (a) => {
console.log('Starting work: ' + a);
// Here we simulate some long operation
for (let i = 0; i < 100000; i++) {
document.querySelector('a[href]');
}
console.log('Finished work: ' + a);
};
work(1);
work(2);
work(3);
setTimeout(() => work(4), 2);
setTimeout(() => work(5), 1);
work(6);
work(7);
您将在输出上看到的是:
Starting work: 1
Finished work: 1
Starting work: 2
Finished work: 2
Starting work: 3
Finished work: 3
Starting work: 6
Finished work: 6
Starting work: 7
Finished work: 7
Starting work: 4 <- This one was async
Finished work: 4 <- This one was async
Starting work: 5 <- This one was async
Finished work: 5 <- This one was async
因此,即使有一些异步代码,函数总是启动和完成,而不会异步代码在执行中途“中断”它。work
添加回答
举报