HTML5 Game Development Blog

  • Tiled Game Engine slide

HTML5 Optimization tips: throttle input and requestAnimationFrame

Category : Tiled Game Engine Mar 3rd, 2015

Pages: 1 2

Well, some short post about user interaction and animation performance. In any game we need some actions from user and, in the same time, we have to run our animation loop with constant frame rate. In that post I’ll cover some techniques how to do  that with minimum impact on frame rate with respect to browser internals: throttle and requestAnimationFrame in hands.

Throttle input

In some cases user event will be fired to often, for example if we’re listening for mousemove or resize events. When you move mouse a lot of events fired and, in some cases, more than 60 times per second. But we actually interested only in few of them and can skip others to decrease CPU load. I use handy utility function for that:

    window.throttle = function(fn, threshold, scope) {
        threshhold || (threshhold = 250);
        var last,
        return function () {
            var context = scope || this,
                now = +new Date,
                args = arguments;
            if (last && now < last + threshhold) {
                // hold on to it
                deferTimer = setTimeout(function () {
                    last = now;
                    fn.apply(context, args);
                }, threshhold);
            } else {
                last = now;
                fn.apply(context, args);

This code will call fn callback with some delay after last function call. Delay is managed by threshold parameter. So, if during threshold time several events will be fired actual event handler will be called just once. Use of that handy wrapper do not require any modifications in the actual event handlers. Let’s see it in action.

In the Screen class constructor, I subscribe to the mouse and window events:

    function Screen(tag, width, height) {
        window.addEventListener('resize', throttle(this.onResize, 64, this));

Screen.onResize callback will be called just once per 4 frames. This is fast enough for user (no noticeable delay) and slow enough to unload CPU and GPU.

Throttling wrapper is very handy and widely used in the interactive on-site search input fields. Each time user type a char “search” request posted to the server. But if user types fast enough a lot of requests will be posted with no actual reason. Throttling user input will be very useful in that case – post “search” event only when user stop typing.

Pages: 1 2


Leave a Reply

Your email address will not be published.

Like it? Share It!

We're making our best to provide good and valuable content. Please help us by clicking on one of the social icons, thanks for everything.