有時候我們希望使用者點擊連結後不要立刻跳走,而是延遲幾秒——常見場景包括先播完一段動效、先顯示提示訊息,或做廣告導流的倒數。用 setTimeout() 就能實現。
<html>
<head>
<title>延遲跳轉示範</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<script type="text/javascript">
function delayURL(url, time) {
setTimeout("top.location.href = '" + url + "'", time);
}
</script>
</head>
<body>
<a href="#" onClick="delayURL('https://www.baidu.com/', 3000)">點擊到百度</a>
</body>
</html>
setTimeout 的第二個參數是毫秒,3000 即 3 秒。
範例中把程式碼寫成字串傳給 setTimeout,這在舊寫法中很常見,但有兩個問題:一是字串會被 eval 執行,效能較差且有安全風險;二是無法直接傳參。建議改用函式:
function delayURL(url, time) {
setTimeout(function () {
top.location.href = url;
}, time);
}
另外,把 href 設為 # 會破壞「用滑鼠中鍵在新分頁開啟」與 SEO 的效果。更友善的做法是保留真實網址,只在需要時攔截:
<a href="https://www.baidu.com/" id="go">點擊到百度</a>
<script>
document.getElementById('go').addEventListener('click', function (e) {
e.preventDefault();
var url = this.href;
setTimeout(function () { location.href = url; }, 3000);
});
</script>
setInterval 每秒更新數字,倒數歸零時再導向。clearTimeout(id),避免使用者重複點擊時觸發多次跳轉。