I have a case where I want a function to fire only when I first type something and fires another function when the I’m done typing (10 seconds idle)
I have this:
JavaScript
x
22
22
1
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');
2
keyPressElements.forEach(function(elem) {
3
elem.addEventListener('keypress', function() {
4
updateLastTypedTime();
5
});
6
});
7
8
function updateLastTypedTime() {
9
if (searchTimeout != undefined)
10
clearTimeout(searchTimeout);
11
isUserTyping = true;
12
console.log("Telling UpdateViewAPI that the user is still typing...");
13
UpdateViewAPI();
14
searchTimeout = setTimeout(callServerScript, 10000);
15
}
16
17
function callServerScript() {
18
console.log("Telling UpdateViewAPI that the user hasn't typed in 10 seconds.");
19
isUserTyping = false;
20
UpdateViewAPI();
21
}
22
But the issue with this is it triggers the updateLastTypedTime() everytime i type.
Thanks!
Advertisement
Answer
It looks like you want another function that’s called from updateLastTypedTime
only if the user was not already typing, something like:
JavaScript
1
9
1
function updateLastTypedTime() {
2
if (searchTimeout != undefined)
3
clearTimeout(searchTimeout);
4
if (!isUserTyping)
5
updateStartTyping();
6
isUserTyping = true;
7
searchTimeout = setTimeout(callServerScript, 10000);
8
}
9
JavaScript
1
27
27
1
var keyPressElements = document.querySelectorAll("#test-input");
2
keyPressElements.forEach(function(elem) {
3
elem.addEventListener('keypress', function() {
4
updateLastTypedTime();
5
});
6
});
7
8
var searchTimeout;
9
var isUserTyping = false;
10
11
function updateLastTypedTime() {
12
if (searchTimeout != undefined)
13
clearTimeout(searchTimeout);
14
if (!isUserTyping)
15
updateStartTyping();
16
isUserTyping = true;
17
searchTimeout = setTimeout(callServerScript, 10000);
18
}
19
20
function updateStartTyping() {
21
console.log("User started typing");
22
}
23
24
function callServerScript() {
25
console.log("User stopped typing.");
26
isUserTyping = false;
27
}
JavaScript
1
1
1
<input type="text" id="test-input">