js 实现暂停
使用 setTimeout 和 clearTimeout 控制暂停
通过 setTimeout 设置延时执行任务,保存返回的 timeoutId,调用 clearTimeout(timeoutId) 可以取消延时任务,实现暂停效果。
let timeoutId;
function startTask() {
timeoutId = setTimeout(() => {
console.log("Task executed");
}, 3000);
}
function pauseTask() {
clearTimeout(timeoutId);
}
使用 Promise 和 async/await 实现可控暂停
通过 Promise 和 async/await 结合标志位控制执行流程,利用 setInterval 轮询检查是否继续执行。
let isPaused = false;
async function runTask() {
while (true) {
if (isPaused) {
await new Promise(resolve => setTimeout(resolve, 100));
continue;
}
console.log("Task running");
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
function togglePause() {
isPaused = !isPaused;
}
使用 Generator 函数分步执行
通过 Generator 函数分步执行任务,外部调用 next() 控制执行进度,实现暂停与继续。
function* taskGenerator() {
yield console.log("Step 1");
yield console.log("Step 2");
yield console.log("Step 3");
}
const task = taskGenerator();
task.next(); // 执行第一步
// 暂停后再次调用 task.next() 继续执行
使用 AbortController 中断异步操作
现代浏览器支持 AbortController,可用于中断 fetch 等异步操作,实现类似暂停的效果。
const controller = new AbortController();
async function fetchData() {
try {
const response = await fetch("https://api.example.com", {
signal: controller.signal
});
console.log(await response.json());
} catch (e) {
if (e.name === "AbortError") {
console.log("Request aborted");
}
}
}
function abortRequest() {
controller.abort();
}
使用 requestAnimationFrame 控制动画暂停
对于动画场景,可通过 requestAnimationFrame 和取消机制实现暂停。
let animationId;
let isAnimating = false;
function animate() {
// 动画逻辑
animationId = requestAnimationFrame(animate);
}
function toggleAnimation() {
if (isAnimating) {
cancelAnimationFrame(animationId);
} else {
animate();
}
isAnimating = !isAnimating;
}
使用 Worker 线程控制
通过 Web Worker 在后台线程执行任务,主线程通过 postMessage 发送暂停指令。

// main.js
const worker = new Worker("worker.js");
worker.postMessage({ command: "start" });
function pauseWorker() {
worker.postMessage({ command: "pause" });
}
// worker.js
let isPaused = false;
self.onmessage = function(e) {
if (e.data.command === "pause") {
isPaused = true;
}
};
每种方法适用于不同场景,根据具体需求选择合适方案。定时器方案适合简单延时任务,Promise 方案适合异步流程控制,Generator 适合分步操作,AbortController 专精网络请求中断,requestAnimationFrame 针对动画,Worker 适用于后台计算任务。






