Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery / backbone.js - delay function call

I have a #search element, which when the keyup event occurs should fire a function. This function should only fire if keyup hasn't occurred in a set amount of time (say 500 milliseconds for example). This will prevent search results from updating every letter that is pressed. The problem is that with backbone.js, I have my events in a hash and the one that is applicable looks like:

'keyup #search' : 'setSearch'

which calls the setSearch() function when the keyup event occurs. I'm not really clear on how to handle it at this point. I've tried a variety of things, but nothing can maintain the timer past the function ending.

I have something like so:

setSearch: function(event) {
            var timer = window.setTimeout( function() {
                // run function here
                alert('fired');
            }, 500);
    },

rather than the alert('fired'), I'll have my own function run. I can see why this code doesn't work (a timer is set for every keyup event that occurs. But I still don't have a clear idea on what else I could try.

like image 618
Matthew Avatar asked Nov 28 '22 18:11

Matthew


1 Answers

What you are looking for is actually a function provided to you from underscore.js (a requirement of Backbone)

 setSearch: _.throttle(function() {
                //Do Stuff
              }, 500),

In a nutshell, this returns a new form of the anonymous function that can only be called once every 500ms. You will likely have to tweak the timing to your needs.

More Info: http://documentcloud.github.com/underscore/#throttle

like image 171
Skylar Anderson Avatar answered Dec 05 '22 08:12

Skylar Anderson