cgmckeever
cgmckeever

Reputation: 4093

js/ajax w/ onkeypress with throttling

working on a dynamic request as a person types. Would like to try to throttle it so not EVERY key press fires off a call.

First thought was to do a setimeout of 1s and clear the timeout with each keypress, therefore waiting till there is a lag of 1s before pushing off the request.

Wondering if there are any cleaner suggestions

Upvotes: 1

Views: 282

Answers (2)

jimutt
jimutt

Reputation: 667

That solution will work well if you don't have a lot of other script that will run simultaneous.

Otherwise you can set up an if loop which triggers the call every 5 keypress for example. Something like this:

if(i == 5) {
    //Execute your call
}

And then you you increase the value of i each time a key is pressed.

But of course there are even more solutions as well.

Upvotes: 0

jakee
jakee

Reputation: 18566

Underscore.js Offers a throttle function that creates a version of a function that is executed only once every x milliseconds. You might want to look into that

Upvotes: 1

Related Questions