โหลดหน้าเว็บใหม่หลังหน่วงเวลา ด้วย setTimeout()
ใช้ setTimeout() ร่วมกับ window.open() เพื่อเปิดหน้าเว็บใหม่ (New Tab/Window) หลังจากจำนวน Milliseconds ที่กำหนด
รูปแบบไวยากรณ์ (Syntax)
setTimeout(function() {
window.open('url', '_blank'); // '_blank' = แท็บใหม่
}, milliseconds);
ตัวอย่างโค้ด: เปิด qries.com ในแท็บใหม่หลัง 5 วินาที
<!DOCTYPE html>
<html>
<body>
<script>
setTimeout(myURL, 5000);
function myURL() {
window.open('https://qries.com'); // หรือ '_blank' โดยค่าเริ่มต้น
}
</script>
<p>Web page loads after 5 seconds.</p>
</body>
</html>
ความแตกต่าง: window.open vs window.location.href
| Method | พฤติกรรม | Use Case |
| window.open('url', '_blank') | เปิดแท็บ/หน้าต่างใหม่ หน้าเดิมยังคงอยู่ | External Link, Popup, New Window |
| window.location.href = 'url' | นำทางหน้าปัจจุบัน (Redirect) แทนที่หน้าเดิม | SPA Navigation, Login Redirect, Page Redirect |
| window.location.replace('url') | Redirect โดยไม่เก็บ History (Back ไม่ได้) | Login Flow, One-time Redirect |
ตัวอย่าง: นับถอยหลัง แล้วเปิดหน้าใหม่
<!DOCTYPE html>
<html>
<body>
<p>Opening in <span id="count">5</span> seconds...</p>
<script>
let sec = 5;
const el = document.getElementById('count');
const timer = setInterval(() => {
sec--;
el.textContent = sec;
if (sec <= 0) {
clearInterval(timer);
window.open('https://example.com', '_blank');
}
}, 1000);
</script>
</body>
</html>
ข้อควรระวัง: Popup Blocker
- Browser ส่วนใหญ่บล็อก
window.open() หากไม่ได้ Trigger จาก User Interaction (Click, Keydown)
- โค้ดที่รันใน
setTimeout โดยตรง อาจถูกบล็อก
- วิธีแก้:
- ผูกกับ Event: ``
- ใช้ `window.location.href` แทน (Redirect หน้าปัจจุบัน)
- แจ้งผู้ใช้ให้ Allow Popups
Best Practice: Fallback สำหรับ No-JS / Blocked Popup
<body>
<p>
Redirecting in 5 seconds...
<br>
<a href="https://example.com" id="fallbackLink">Click here if not redirected</a>
</p>
<script>
setTimeout(() => {
const opened = window.open('https://example.com', '_blank');
if (!opened || opened.closed || typeof opened.closed == 'undefined') {
// Popup Blocked -> Fallback to Redirect
window.location.href = 'https://example.com';
}
}, 5000);
</script>
<noscript>
<meta http-equiv="refresh" content="5; url=https://example.com">
</noscript>
</body>
สรุป
ใช้ setTimeout(() => window.open('url', '_blank'), 5000) เพื่อโหลดหน้าเว็บใหม่ในแท็บแยกหลัง 5 วินาที แต่ต้องระวัง Popup Blocker แนะนำให้มี Fallback Link และ Meta Refresh สำหรับกรณี JavaScript ถูกปิด