Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách tải trang web sau 5 giây bằng JavaScript

Sử dụng setTimeout + window.open

<!DOCTYPE html>
<html>
<body>
  <script>
    setTimeout(myURL, 5000);
    function myURL() {
      window.open('https://qries.com');
    }
  </script>
  <p>Trang web tải sau 5 giây.</p>
</body>
</html>

Phân biệt: load trong tab hiện tại vs tab mới

Phương phápHành viDùng khi
window.location.href = urlTải trong tab hiện tạiRedirect, chuyển trang
window.location.replace(url)Tải tab hiện tại, không lưu historyRedirect sau login, tránh Back
window.open(url)Mở tab/cửa sổ mớiLink ngoài, popup, quảng cáo
window.open(url, '_self')Tải tab hiện tại (giống href)Ít dùng

Chặn popup

Trình duyệt thường chặn window.open nếu không phải hành động người dùng trực tiếp (click). Trong ví dụ trên, setTimeout tách biệt sự kiện click → có thể bị chặn.

Giải pháp: Gán setTimeout trong handler click, hoặc dùng location.href.

Ví dụ an toàn (không bị chặn)

<button id="btn">Mở sau 5s</button>
<script>
document.getElementById('btn').addEventListener('click', function() {
  setTimeout(function() {
    window.open('https://example.com', '_blank');
  }, 5000);
});