У меня проблема с моим скриптом
я хочу обновлять страницу каждые 30 секунд,
Но ТОЛЬКО когда вы НЕ печатаете в текстовое поле
ДРУГОЕ ВАЖНОЕ
страница должна обновляться, если я печатаю в текстовое поле, и я останавливаюсь, не нажимая кнопку отправки в течение 1 минуты (в режиме ожидания)
<!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>
Вместо проверки «isTyping» вы можете отменить setTimeout и создавать новый каждый раз, когда пользователь что-то делает.
Вот реализация (тайм-аут изменен на x100 мс вместо x1000 только для тестирования и некоторый вывод, чтобы увидеть, что происходит)
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>