简体   繁体   English

使用空闲计时器重定向页面

[英]Redirecting Page with idle timer

I'm trying to redirect the user to another page after the user is idle for 30 minutes.在用户空闲 30 分钟后,我试图将用户重定向到另一个页面。 How do I do this?我该怎么做呢? I'm horrible at JS so I haven't tried anything.我在 JS 方面很糟糕,所以我什么都没试过。

The idle timer code only shows how long the user has been idle for.空闲计时器代码仅显示用户空闲的时间。

 <!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>
Credits to Geeks for Geeks for original idle code 归功于 Geeks for Geeks 的原始空闲代码

Use setTimeout instead like in this answer .使用setTimeout代替这个答案

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

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

And when you're testing, just change the second parameter to setTimeout like so:当您进行测试时,只需将第二个参数更改为setTimeout如下所示:

timer = setTimeout(redirectUser, 5000);

It's the amount of time in milliseconds before it executes the function passed as the first parameter.它是执行作为第一个参数传递的函数之前的时间量(以毫秒为单位)。

 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