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:
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(); }
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:
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">