Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clearTimeout not working in javascript autocomplete script

I am using the following code as part of an autocomplete script to avoid hammering the server with every keystroke:

var that = this;

textInput.bind("keyup", function() {

    clearTimeout(that.timer);

    that.timer = setTimeout (that.doStuff(), 2000);

});

Unfortunately, this does not clear the old timers. They still all execute.

Does anyone know what I'm missing?

Thanks!

like image 945
Travis Avatar asked Apr 11 '10 22:04

Travis


1 Answers

You probably want to use:

that.timer = setTimeout (that.doStuff, 2000);

instead of:

that.timer = setTimeout (that.doStuff(), 2000);

Otherwise, doStuff will be called immediately.

like image 151
interjay Avatar answered Sep 22 '22 02:09

interjay