Home > front end >  Refreshing page
Refreshing page

Time:03-31

Am having a problem with my script

i want to refresh the page every 30 seconds,

But ONLY when you are NOT typing into textbox

OTHER IMPORTANT THING

page should refresh if am typing into textbox and i stop without clicking send button for 1 minute (Idle)

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
var isTyping = false;
$("#inputbox").focus(function() {
    isTyping = true;
});
$("#inputbox").blur(function() {
    isTyping = false;
});

// Refresh page, but ONLY when you are NOT typing
var refreshId = setInterval(function() {
    if (!isTyping) {
        window.setTimeout( function() {
  window.location.reload();
)}, 30000); 
    }
)}
$.ajaxSetup({ cache: false });
</script>
</head>
<body>

<input type="text" id="inputbox">
<button type="button">Click Me!</button> 
</body>
</html>

CodePudding user response:

Rather than check for "isTyping", you can cancel the setTimeout and create a new one each time the user does something.

  • Cancel/start a new timer (60s) on focus/input.
  • Cancel/start a new timer (30s) on blur.
  • Start the timeout when the page loads.

Here's the implementation (timeout changed to x100 ms instead of x1000 just for testing and some output to see what's happening)

var timerId;

function restartTimer(s) {
  clearInterval(timerId);
  timerId = setTimeout(() => {
    //window.location.reload()
    $("#out").text("times up");
  }, s * 100  /* * 1000, 100 for testing */);

  $("#out").text("timer restarted: "   s   "s "   timerId);
}

$("input").on("focus input", () => restartTimer(60));
$("input").on("blur", () => restartTimer(30));

// "technically" startTimer, but it's the same
restartTimer(30);

// optionally only if "idle"
//$("document").on("mousemove click", () => restartTimer(30));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<input type="text" id="inputbox">
<button type="button">Click Me!</button>

<div id="out"></div>

  • Related