Reputation: 511
Hi I have created the below time out function that runs either 2 seconds after the person has finished typing or on pressing enter. It works as described but for some reason i get the function repeating. For instance if i type 5 letter and wait 5 2 seconds i get 5 alerts after two seconds. I want just to receive 1 alert. What do i need to change?
function doSearch()
{
//run js function half a second after typing has stopped
var typingTimer; //timer identifier
var doneTypingInterval = 2000;
$(document).keypress(function(e){
$('#txtSearch').keypress(function(e){
if(e.keyCode == 13)
{
clearTimeout(typingTimer);
alert("pressesd");
}
});
//on keyup, start the countdown
$('#txtSearch').keyup(function(){
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//user is "finished typing," do somethin
function doneTyping()
{
alert("done");
clearTimeout(typingTimer);
}
}
Thank s in advance
Upvotes: 0
Views: 305
Reputation: 96
Append the keypress event in document.ready
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script language="javascript">
var typingTimer = null; //timer identifier
var doneTypingInterval = 2000;
$(document).ready(function (e) {
$('#txtSearch').keyup(function (e) {
if (e.keyCode == 13) {
doneTyping();
}
else {
if (typingTimer != null)
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, 5000);
}
});
});
//user is "finished typing," do something
function doneTyping() {
clearTimeout(typingTimer);
alert("done");
}
</script>
Upvotes: 0
Reputation: 11106
you have several syntax errors in your script. Altered code:
var typingTimer; //timer identifier
function doSearch()
{
//run js function half a second after typing has stopped
var doneTypingInterval = 2000;
//on keyup, start the countdown
$('#txtSearch').keyup(function(e){
if(e.keyCode == 13)
{
clearTimeout(typingTimer);
alert("pressesd");
}
else
{
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
}
//user is "finished typing," do somethin
function doneTyping()
{
alert("done");
clearTimeout(typingTimer);
}
working fiddle here.
Edited the fiddle, now it really works :/
Upvotes: 1
Reputation: 1371
Do not use keyup
event to clear the event, use keypress
event instead.
var el = document.getElementById('input');
var timeOutId;
el.addEventListener('keypress', onKeyPress);
function onKeyPress(event){
if(event.keyCode == 13){
doStuff();
return;
}
clearTimeout(timeOutId);
timeOutId = setTimeout(doStuff, 2000);
}
function doStuff(){
console.log('Doing Stuff');
}
Upvotes: 0