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

Cách chuyển hướng trang web sau 5 giây bằng JavaScript

Sử dụng setTimeout + window.location

<!DOCTYPE html>
<html>
<body>
  <script>
    setTimeout(function() {
      window.location.href = 'https://www.tutorialspoint.com/javascript/';
    }, 5000); // 5000ms = 5 giây
  </script>
  <p>Trang sẽ chuyển hướng sau 5 giây.</p>
</body>
</html>

Các cách gán URL

  • window.location.href = url – thêm vào history (bấm Back được).
  • window.location.assign(url) – giống href.
  • window.location.replace(url) – thay thế history hiện tại (không Back được). Khuyên dùng cho redirect sau login.

Hủy chuyển hướng

var timer = setTimeout(redirect, 5000);
function redirect() { window.location.replace(target); }

// Nếu user click "Hủy"
document.getElementById('cancelBtn').onclick = function() {
  clearTimeout(timer);
};

Lưu ý

  • Độ trễ tối thiểu ~4ms trong tab background.
  • Tránh lặp vô tận: redirect đến trang cũng chạy script redirect.