簡體   English   中英

使用空閑計時器重定向頁面

[英]Redirecting Page with idle timer

在用戶空閑 30 分鍾后,我試圖將用戶重定向到另一個頁面。 我該怎么做呢? 我在 JS 方面很糟糕,所以我什么都沒試過。

空閑計時器代碼僅顯示用戶空閑的時間。

 <!DOCTYPE html> <html> <head> <title> Test </title> <!-- import the webpage's stylesheet --> <link rel="stylesheet" href="/style.css" /> <!-- import the webpage's javascript file --> <script src="/script.js" defer></script> </head> <body> <div class="idle"> <p class="timertext"> <span class="secs"></span> </p> </div> <script> let timer, currSeconds = 0; function resetTimer() { /* Hide the timer text */ document.querySelector(".timertext").style.display = "none"; /* Clear the previous interval */ clearInterval(timer); /* Reset the seconds of the timer */ currSeconds = 0; timer = setInterval(startIdleTimer, 1000); } window.onload = resetTimer; window.onmousemove = resetTimer; window.onmousedown = resetTimer; window.ontouchstart = resetTimer; window.onclick = resetTimer; window.onkeypress = resetTimer; function startIdleTimer() { /* Increment the timer seconds */ currSeconds++; /* Set the timer text to the new value */ document.querySelector(".secs").textContent = currSeconds; /* Display the timer text */ document.querySelector(".timertext").style.display = "block"; } </script> </body> </html>
歸功於 Geeks for Geeks 的原始空閑代碼

使用setTimeout代替這個答案

timer = setTimeout(redirectUser , 30 * 60 * 1000);

function redirectUser() {
  window.location.href = 'https://mylink.com';
}

當您進行測試時,只需將第二個參數更改為setTimeout如下所示:

timer = setTimeout(redirectUser, 5000);

它是執行作為第一個參數傳遞的函數之前的時間量(以毫秒為單位)。

 var timer; function resetTimer() { clearTimeout(timer); timer = setTimeout(redirectUser, 30 * 60 * 1000); } function redirectUser() { window.location.href = 'https://redirecturl'; } window.onload = resetTimer; window.onmousemove = resetTimer; window.onmousedown = resetTimer; window.ontouchstart = resetTimer; window.onclick = resetTimer; window.onkeypress = resetTimer;
 <!DOCTYPE html> <html> <head> <title> Test </title> <!-- import the webpage's stylesheet --> <link rel="stylesheet" href="/style.css" /> <!-- import the webpage's javascript file --> <script src="/script.js" defer></script> </head> <body> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM