LoginSignup
1
1

More than 5 years have passed since last update.

Throttleを実装してみる

Posted at

resizeやmousemoveなど、多数発火するイベントを間引く処理の実装。

function Throttle(ms) {

    var _timer,
        prevTime;

    function exec(func) {

        var now = +new Date(),
            delta;

        if (typeof func !== 'function') {
            return false;
        }

        if (!prevTime) {
            func();
            prevTime = now;
            return;
        }

        clearTimeout(_timer);
        delta = now - prevTime;
        if (delta > ms) {
            func();
            prevTime = now;
        }
        else {
            _timer = setTimeout(function () {
                func();
                _timer = null;
                prevTime = now;
            }, ms);
        }
    }

    return {
        exec: exec
    };
}

/*! --------------------------
    使用例
------------------------------ */
var throttle = new Throttle(1000),
    i = 0,
    timer;

timer = setInterval(function () {
    i++;
    if (i > 10) {
        clearInterval(timer);
        console.log(i);
        return false;
    }
    var j = i;
    throttle.exec(function () {
        console.log(j);
    });
}, 32);
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1