检测用户第一次键入和最后一次键入的时间,而不是介于两者之间



我有一种情况,我希望一个函数只在我第一次键入某个东西时激发,并在我键入完(空闲10秒(时激发另一个函数

我有这个:

var keyPressElements = document.querySelectorAll('#waste-form input,#address,.container .form-control,.widget-box .form-control,#aria-main-search-form-field,#footer-search-field,#aria-feedback-form-field');
keyPressElements.forEach(function(elem) {
elem.addEventListener('keypress', function() {
updateLastTypedTime();
});
});

function updateLastTypedTime() {
if (searchTimeout != undefined)
clearTimeout(searchTimeout);
isUserTyping = true;
console.log("Telling UpdateViewAPI that the user is still typing...");
UpdateViewAPI();
searchTimeout = setTimeout(callServerScript, 10000);
}
function callServerScript() {
console.log("Telling UpdateViewAPI that the user hasn't typed in 10 seconds.");
isUserTyping = false;
UpdateViewAPI();
}

但问题是,每次我键入时,它都会触发updateLastTypedTime((。

谢谢!

看起来你想要另一个从updateLastTypedTime调用的函数,只有当用户还没有键入时,比如:

function updateLastTypedTime() {
if (searchTimeout != undefined)
clearTimeout(searchTimeout);
if (!isUserTyping)
updateStartTyping();
isUserTyping = true;
searchTimeout = setTimeout(callServerScript, 10000);
}

var keyPressElements = document.querySelectorAll("#test-input");
keyPressElements.forEach(function(elem) {
elem.addEventListener('keypress', function() {
updateLastTypedTime();
});
});
var searchTimeout;
var isUserTyping = false;

function updateLastTypedTime() {
if (searchTimeout != undefined)
clearTimeout(searchTimeout);
if (!isUserTyping)
updateStartTyping();
isUserTyping = true;
searchTimeout = setTimeout(callServerScript, 10000);
}
function updateStartTyping() {
console.log("User started typing");
}
function callServerScript() {
console.log("User stopped typing.");
isUserTyping = false;
}
<input type="text" id="test-input">

相关内容

  • 没有找到相关文章

最新更新