Throttling server-side call based on keyup


#1

I have a Method call (server-side) that queries an external API on keyup, not the best in terms of performance and I’m hitting the API pretty hard. Is there some way to throttle the method call? Essentially waiting with the request until a certain delay has passed after the last keystroke.


#2

I’d probably do it something like this:

Template.something.onCreated(function() {
  this.debounce = null;
});

Template.something.events({
  'keyup input#some-id': function() {
    var instance = Template.instance();
    if (instance.debounce) {
      Meteor.clearTimeout(instance.debounce);
    }
    instance.debounce = Meteor.setTimeout(function() {
      Meteor.call(...);
    }, 200);
  }
});

#3

Great, thanks! :smile:


#4

@robfallows is right, you’ll want to debounce your function… Since underscore is part of core though you might as well use underscores debounce function

Template.something.events({
  'keyup input#some-id': _.debounce(function() {
     //code here
  }, 200);
});

edit: fix typo => _debounce


#5

That is much more compact :smile:.

However, you should add the underscore package to your app if you use this (even though it’s currently in the core).


#6

I have debounce as package too and using it this way, which way is the best from compatibility point of view?

Template.searchForm.events({
     "keyup #searchStreamer": _.debounce(function (event, template) {
    	RunSearch({searchStreamer: event.target.value, searchSkip: 0});
   },1000)
...

use _debounce, or _.debounce or how? :smiley:


#7

Well spotted: _.debounce() is correct: http://underscorejs.org/#debounce

:smile:


#8

that’s great. thank you