Search code examples
javascriptjquerybackbone.jsdom-eventssettimeout

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.


Solution

  • You need an instance variable in your view that stores the timer ID, then you can stop it and restart it as needed:

    setSearch: function(event) {
        var self = this;
        if(self.timer)
            clearTimeout(self.timer);
        self.timer = setTimeout(function() {
            alert('fired');
            self.timer = null;
        }, 500);
    }
    

    So, if the timer is already running, you call clearTimeout to stop it, start a new timer, and store the timer ID in self.timer (AKA this.timer). You'll also want to reset the stored timer ID in the timer's callback function or your setSearch won't do anything after its timer has fired once. And all the self business is just to capture this for use in the timer's callback function.