Hey guys whilst I was trying to solve this issue I came across your thread which I found helpful to an extent, basically I spent hours reading up and realised that the solutions you provided doesn't do what you actually wanted it to do so here I offer my solution.
In a new thread to be clear and this is my first post so, please read ;)
The answers you give don't actually clear the timer since it is in the function after the one you have just executed let me explain...
function doSomething() {
if(timeout) clearTimeout(timeout);
var timeout = setTimeout(function() {
// your function code
}, 2000);
}
When you call doSomething() twice the second call is queued and isn't executed till the entire function as finished so therefore the clearTimeout call is pointless since the entire first call as already been executed... this included the time-out you have set.
So time for my solution, is if this is for a user input field is quite simple and cheeky.
Retrieve the length of the input box outside of the timeout and then also inside and check they are the same length. This isn;t a brilliantly slimline solution as it technically executes the "function" but as you can see it executes 2 or 3 lines of it ;), and strips the bulk of your code.
function doSomething() {
var outside = getElementById("inputid").value;
var timeout = setTimeout(function() {
var inside = getElementById("inputid").value;
if(inside.length != outside.length) {return}
// if lengths have changed during the time out period the function stops....the next one executes but again stops after 4 lines if the user continues to type, if they have stopped you will continue to....
// your function code
}, 2000);
}
I hope this gets read and some of you veteran coders give your opinions or point out any problems with this code.