Redirect ด้วย JavaScript (setTimeout)
ใช้ setTimeout() ร่วมกับ window.location.href เพื่อเปลี่ยนหน้าหลังจากเวลาที่กำหนด (Milliseconds)
รูปแบบไวยากรณ์ (Syntax)
setTimeout(function() {
window.location.href = 'target_url';
}, milliseconds);
ตัวอย่างโค้ด: Redirect ไป tutorialspoint.com/javascript หลัง 5 วินาที (5000 ms)
<!DOCTYPE html>
<html>
<body>
<script>
setTimeout(function() {
window.location.href = 'https://www.tutorialspoint.com/javascript/';
}, 5000);
</script>
<p>Web page redirects after 5 seconds.</p>
</body>
</html>
วิธีการอื่นๆ ในการ Redirect ด้วย JavaScript
| วิธี | โค้ด | คำอธิบาย |
| window.location.href | window.location.href = 'url' | เพิ่ม History ใช้ Back Button กลับได้ (แนะนำ) |
| window.location.replace | window.location.replace('url') | แทนที่ History ใช้ Back Button กลับไม่ได้ |
| window.location.assign | window.location.assign('url') | คล้าย href แต่เป็น Method |
| window.location | window.location = 'url' | Shortcut ของ href |
ตัวอย่าง: Redirect พร้อม Countdown Timer
<!DOCTYPE html>
<html>
<body>
<p>Redirecting in <span id="countdown">5</span> seconds...</p>
<script>
var seconds = 5;
var countdownEl = document.getElementById('countdown');
var timer = setInterval(function() {
seconds--;
countdownEl.textContent = seconds;
if (seconds <= 0) {
clearInterval(timer);
window.location.href = 'https://example.com';
}
}, 1000);
</script>
</body>
</html>
ข้อดีของ JavaScript Redirect
- สามารถทำ Logic ได้: เงื่อนไข, ตัวแปร, User Interaction
- แสดง Countdown / Progress ให้ผู้ใช้เห็น
- สามารถส่งข้อมูล (Query Params, POST via Form) ได้
- ควบคุม History (replace vs assign)
ข้อควรระวัง
- Browser อาจบล็อก Pop-up/Redirect หากไม่ได้จาก User Action
- ผู้ใช้ปิด JavaScript → ไม่ทำงาน (ต้องมี Fallback: Meta Tag หรือ Link)
- SEO: Google Bot ตอนนี้ Render JS ได้ แต่ Server-side Redirect (301/302) ยังดีกว่า
Best Practice: รวม Meta Tag + JavaScript
<head>
<meta http-equiv="refresh" content="5; url=https://example.com">
<noscript>
<meta http-equiv="refresh" content="0; url=https://example.com">
</noscript>
</head>
<body>
<p>Redirecting... <a href="https://example.com">Click here if not redirected</a></p>
<script>
setTimeout(() => window.location.href = 'https://example.com', 5000);
</script>
</body>
สรุป
ใช้ setTimeout(() => window.location.href = 'url', 5000) สำหรับ Redirect หลัง 5 วินาที พร้อม Countdown UI แนะนำรวม Meta Tag Fallback สำหรับ No-JS และ SEO