Function#debounce Useful JavaScript Game Extension #36

I got this from Underscore.js.

###*
Calling a debounced function will postpone its execution until after 
wait milliseconds have elapsed since the last time the function was 
invoked. Useful for implementing behavior that should only happen after 
the input has stopped arriving. For example: rendering a preview of a 
Markdown comment, recalculating a layout after the window has stopped 
being resized...
 
lazyLayout = calculateLayout.debounce(300)
$(window).resize(lazyLayout)
 
@name debounce
@methodOf Function#
@returns {Function} The debounced version of this function.
###
Function::debounce = (wait) ->
  timeout = null
  func = this
 
  return ->
    context = this
    args = arguments
 
    later = ->
      timeout = null
      func.apply(context, args)
 
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)

Already I can see an important use for it. In the code editor we copy out the buffer every keyup. This can lead to a bunch of extra work for the browser when typing. Usually it’s not a big deal because the files are generally small, but on larger files it can add up and cause some lagging. When using debounce the editor will only trigger after enough milliseconds have elapsed since the end of new keyup events. This will keep the IDE from lagging on larger files while you are typing.

Another place debounce is useful is in a game that implements a Halo style health regeneration. Every time the player takes damage a debounced startRegen function could be called. That way the regen will only start after enough time without taking damage has elapsed. In the game version it would probably be better to constrain it to ticks of the engine, or engine elapsed time for more accuracy.

I’m always a big fan of Function functions, they are a great way to reduce boilerplate and solve higher-order problems.

One thought on “Function#debounce Useful JavaScript Game Extension #36

  1. I’ve definitely found debounce to be useful when dealing with actions like saving or anything else that could lag out the program if called 100 times a second

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>