Reputation: 19
I'm trying to redirect the user to another page after the user is idle for 30 minutes. How do I do this? I'm horrible at JS so I haven't tried anything.
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>
Upvotes: 0
Views: 551
Reputation: 427
Use setTimeout
instead like in this answer.
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:
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>
Upvotes: 1