Throttle function calls

A throttle function is a function that limit the number of calls to 1 per x time units.
I recently wanted to capture the mousemove event and reset a timer when the mouse was moved. Since the mousemove event is triggered several times per second I don’t want my reset function to be called every time. It would be fine for my reset function to be called once every 5 seconds or something like that.
Resetting a timer is quite cheap, but if I wanted to do something expensive the app would be very sluggish doing these expensive operations too often.

So I came up with this function, written in Coffeescript.

throttle = (func, wait) ->
  last_timestamp = null
  limit = wait
  ->
    context = @
    args = arguments
    now = Date.now()
    if !last_timestamp || now - last_timestamp >= limit
      last_timestamp = now
      func.apply(context, args)

mythrottle = throttle(
  (e) ->
    console.log e
,
  5000
)

elem.bind('mousemove', (e)->
  mythrottle(e)
)

And in Javascript.

var throttle = function(func, wait) {
  var last_timestamp, limit;
  last_timestamp = null;
  limit = wait;
  return function() {
    var args, context, now;
    context = this;
    args = arguments;
    now = Date.now();
    if (!last_timestamp || now - last_timestamp >= limit) {
      last_timestamp = now;
      return func.apply(context, args);
    }
  };
};

var mythrottle = throttle(function(e) {
  return console.log(e);
}, 5000);

elem.bind('mousemove', function(e) {
  return mythrottle(e);
});    

elem is the selected element, like $('#id') in jQuery.

We’re calling mythrottle(e) every 5 seconds on constant mousemove now, instead of several times every second.