js阻塞实现
阻塞实现的方法
在JavaScript中,阻塞通常指同步操作阻止代码继续执行,直到当前任务完成。以下是几种常见的阻塞实现方法:
同步XMLHttpRequest
使用XMLHttpRequest对象进行同步请求,会阻塞代码执行直到请求完成。
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com', false); // 同步请求
xhr.send();
console.log(xhr.responseText); // 请求完成后才会执行
同步函数调用 通过循环或递归实现长时间运行的同步操作,会阻塞事件循环。
function block(ms) {
const start = Date.now();
while (Date.now() - start < ms) {}
}
block(5000); // 阻塞5秒
alert/confirm/prompt 浏览器内置的弹窗方法会阻塞UI线程和JavaScript执行。
alert('This will block execution');
console.log('This logs after alert is closed');
注意事项
- 同步操作会严重影响用户体验,导致页面无响应。
- 现代前端开发中应尽量避免阻塞操作,改用异步方案(如Promise、async/await)。
- Node.js中可以使用
child_process或worker_threads实现非阻塞的并行处理。
替代方案
对于需要等待的操作,推荐使用异步模式:

// 使用Promise替代阻塞
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function nonBlockingWait() {
await delay(5000);
console.log('5秒后执行');
}
nonBlockingWait();






