點擊連結後延遲跳轉常用於倒數計時、廣告展示、表單提交後導向。核心 API 為 setTimeout(),搭配 location.href 或 location.assign() 實現。
function delayRedirect(url, ms) {
setTimeout(() => {
window.location.href = url;
// 或 location.assign(url) - 可被瀏覽器攔截/記錄歷史
}, ms);
}
// 使用
// <a href="#" onclick="delayRedirect('https://example.com', 3000); return false;">
// 3 秒後跳轉
// </a>
class DelayedRedirect {
constructor(url, delayMs, onTick) {
this.url = url;
this.delayMs = delayMs;
this.onTick = onTick;
this.timerId = null;
this.remaining = delayMs;
}
start() {
this.timerId = setInterval(() => {
this.remaining -= 1000;
this.onTick?.(this.remaining);
if (this.remaining <= 0) this.execute();
}, 1000);
}
cancel() {
clearInterval(this.timerId);
this.timerId = null;
}
execute() {
this.cancel();
window.location.href = this.url;
}
}
// 使用
const redirector = new DelayedRedirect('https://example.com', 5000, ms => {
document.getElementById('countdown').textContent = ms / 1000;
});
redirector.start();
// 用戶點擊取消
document.getElementById('cancel').onclick = () => redirector.cancel();
onclick 必須 return false 防止預設跳轉。location.replace(url) 不留歷史,用戶無法返回。簡單需求用 setTimeout 即可;複雜互動請封裝可取消、可暫停、可顯示倒數的元件,提升用戶體驗與可控性。