JavaScript 沒有類似 PHP `exit()` 或 Java `return`(在主流程中)的直接「終止腳本」語句。本文分析各種中止執行的方法、適用場景與副作用,提供最佳實踐建議。
非函數代碼塊中,無法在當前頁面「優雅」中止執行並保持頁面不變。 只有 `throw` 拋出異常或 `location.href` 跳轉兩條路。
function foo() {
console.log(1);
return; // 終止函數
console.log(2); // 不執行
}
foo(); // 輸出 1
// 全局腳本中 return 是語法錯誤
// return; // SyntaxError: Illegal return statement
console.log(1);
throw new Error("主動終止"); // 控制台紅色報錯
console.log(2); // 不執行
// 捕獲可防止冒泡到控制台
try {
throw "STOP"; // 拋出任意值
} catch(e) {
if (e === "STOP") console.log("受控終止");
else throw e; // 重新拋出真實錯誤
}
缺點:污染錯誤監控、控制台紅字、可能觸發全局錯誤處理器(如 Sentry)。
console.log(1);
location.href = "/other-page"; // 當前頁面腳本立即停止,跳轉新頁
console.log(2); // 不會執行
本質是離開當前執行上下文,非真正意義上的「中止」。
// ❌ 想中止後續代碼
if (!condition) {
// 這裡想停止
}
doSomething();
doMore();
// ✅ 正確結構:用 if-else 包裹後續邏輯
if (condition) {
doSomething();
doMore();
} else {
// 可選:處理不滿足條件的情況
}
// ✅ 或提前返回(在函數中)
function handle() {
if (!condition) return;
doSomething();
doMore();
}
(function main() {
console.log(1);
if (!check()) return; // 相當於「主程序」返回
console.log(2);
doSomething();
})();
// 或箭頭函數
(() => {
// 你的所有代碼
if (!ok) return;
})();
$("#form").on("submit", function(e) {
if (!valid) {
e.preventDefault(); // 阻止默認提交
return false; // 阻止事件冒泡 + 返回 false (jQuery 習慣)
}
// 繼續提交...
});
function fetchData() {
if (!userLoggedIn) {
showLoginModal();
return; // 終止當前函數
}
// 發起請求...
}
// Promise 取消模式
var cancelled = false;
function longTask() {
return new Promise((resolve, reject) => {
var id = setInterval(() => {
if (cancelled) {
clearInterval(id);
reject({cancelled: true});
return;
}
// 做事情...
}, 100);
});
}
// 使用
longTask().catch(e => {
if (!e.cancelled) handleError(e);
});
// 主線程
var worker = new Worker("task.js");
worker.terminate(); // 強制終止 Worker
// Worker 內部
self.onmessage = function(e) {
if (e.data === "STOP") self.close(); // 優雅退出
};
| 場景 | 推薦方式 | 避免方式 |
|---|---|---|
| 函數內提前退出 | return | throw |
| 事件處理器阻止默認/冒泡 | e.preventDefault() / return false | throw |
| 全局腳本邏輯分支 | IIFE 包裹 + return / if-else 結構化 | throw / location.href |
| 異步操作取消 | 標誌位 / AbortController / Promise 取消模式 | throw |
| 頁面跳轉/重定向 | location.href / location.replace() | -- |
「結構化程序設計」比「goto 式中止」更優雅。合理組織代碼結構、善用函數返回值、採用現代異步控制流,是解決「中止執行」需求的正規軍之道。