vue循环实现阻塞
在 Vue 中实现阻塞循环
Vue 本身是响应式的,直接使用 for 或 while 循环会导致页面卡死。可以通过异步方式模拟阻塞效果。

使用 setTimeout 分块处理
通过将循环拆分为多个小块,利用 setTimeout 避免阻塞主线程:

function blockingLoop(array, callback, chunkSize = 10) {
let index = 0;
function nextChunk() {
const end = Math.min(index + chunkSize, array.length);
for (; index < end; index++) {
callback(array[index], index);
}
if (index < array.length) {
setTimeout(nextChunk, 0);
}
}
nextChunk();
}
使用 async/await 实现可控延迟
结合 Promise 和 setTimeout 实现延迟效果:
async function blockingAsyncLoop(array, callback, delay = 100) {
for (let i = 0; i < array.length; i++) {
await new Promise(resolve => setTimeout(resolve, delay));
callback(array[i], i);
}
}
Web Worker 方案
对于计算密集型任务,使用 Web Worker 避免阻塞 UI 线程:
// worker.js
self.onmessage = function(e) {
const result = heavyTask(e.data);
self.postMessage(result);
};
// Vue 组件中
const worker = new Worker('worker.js');
worker.postMessage(data);
worker.onmessage = function(e) {
console.log(e.data);
};
注意事项
- 避免在循环中直接操作 DOM,应通过 Vue 的数据驱动机制更新
- 长时间任务建议显示进度条或加载状态
- 大量数据考虑分页或虚拟滚动方案
以上方法可根据实际场景选择,核心思路是将同步阻塞转化为异步非阻塞操作。






