I want to fire an ajax action when user make a pause in typing (instead of after every keypressed). So I made something like this:
When the user stops typing after 3 secs of being idle function done is to be executed … (it is – but why 3 times for long phrases – I would expect it to run only once since I clear timeout after every keydown). What is the problem ?
var timer;
var interval = 3000;
$('#inp').keyup(function() {
timer = setTimeout(done, interval);
});
$('#inp').keydown(function() {
clearTimeout(timer)
});
function done() {
console.log('ajax');
}
Working example on jsfiddle :
http://jsfiddle.net/vtwVH/
The Problem is you are overwriting the
timervariable in your keydown event.So if you press another key before the Timout gets cleared e.g keep holding a key
The reference to the timeOut is lost and you cannot clear it again.
To fix this you could just clear and set the Timer in the
keyUpevent likeHeres a working fiddle