liveBook · Manning

Rate limit

As explained in Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond

A rate-limiting technique that ensures a function is not invoked more often than allowed by a specified schedule.

When a game checks for a spacebar press on every rendered frame, firing a rocket on every check is too fast. Throttling wraps a function and returns a throttled function, limiting how often that action runs. section 29.3

next() {
  super.next();                     1

  if (isPressingSpace()) {          2
    this.fire();                    3
  }

  return this;                      4
}
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":1,\"ch\":36},{\"line\":1,\"ch\":37}],[{\"line\":3,\"ch\":36},{\"line\":3,\"ch\":37}],[{\"line\":4,\"ch\":36},{\"line\":4,\"ch\":37}],[{\"line\":7,\"ch\":36},{\"line\":7,\"ch\":37}]]"}
!@%STYLE%@!

The update hook checks for the spacebar, calls fire when pressed, and returns the ship. section 29.3

export default class Ship extends ControllableSprite {
  static shape = shape;
  static stroke = '#fff';

  fire = throttle(() => {                                     1
    const x = getSpriteProperty(this, 'x');
    const y = getSpriteProperty(this, 'y');
    const rotation = getSpriteProperty(this, 'rotation');

    new Rocket({ x, y, rotation });
  });

  ...
}
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":4,\"ch\":62},{\"line\":4,\"ch\":63}]]"}
!@%STYLE%@!

The ship’s fire property holds a throttled arrow function that creates a rocket. Because it is an instance property rather than a prototype method, subclasses cannot override it with super.fire. section 29.3

How Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond covers it

How deep it goes
Defines throttling as wrapping a function and demonstrates its use; timing intervals and implementation details are unspecified.
Examples
Demonstrates throttling a ship’s fire action while checking spacebar input during each frame.
What you can do after
Apply throttling by wrapping a class-property arrow function and invoking it from the update hook.
How it connects
Connects throttling to JavaScript class properties, method overriding, and decorators as an alternative.

Also explained in

Compare how 14 books explain rate limit →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond. The section links point to the parts of the book it draws on.