萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 延遲跳轉實作:setTimeout 與最佳實踐

前言

點擊連結後延遲跳轉常用於倒數計時、廣告展示、表單提交後導向。核心 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();

注意事項

  • 返回 false:內聯 onclick 必須 return false 防止預設跳轉。
  • 歷史記錄:location.replace(url) 不留歷史,用戶無法返回。
  • 同源策略:跨域跳轉無限制,但無法在跳轉前執行目標域腳本。
  • 無障礙:提供可見倒數與取消按鈕,符合 WCAG 2.1 時間調整準則。

總結

簡單需求用 setTimeout 即可;複雜互動請封裝可取消、可暫停、可顯示倒數的元件,提升用戶體驗與可控性。

copyright © 萬盛學電腦網 all rights reserved