/**
 * Requests animation frames for the specified duration.
 * Calls the callback for every valid animation frame with the progress number (0 <= position <= 1)
 *
 * @param {number} duration
 * @param {number} maxFPS
 * @param {FrameGeneratorStepCallback} cb
 * @returns {FrameGenerator}
 */
export var createFrameGenerator = function (duration, maxFPS, cb) {
    var interval = 1000 / maxFPS;
    var frame;
    var cancel;
    var donePromise = new Promise(function (resolve, reject) {
        var last = Date.now();
        var passed = 0;
        var step = function () {
            var now = Date.now();
            var diff = now - last;
            if (diff < interval) {
                frame = window.requestAnimationFrame(step);
                return;
            }
            last = now;
            passed += diff;
            var percentPassed = (1 / duration) * passed;
            percentPassed = Math.min(percentPassed, 1);
            cb(percentPassed);
            if (percentPassed === 1) {
                return resolve();
            }
            frame = window.requestAnimationFrame(step);
        };
        frame = window.requestAnimationFrame(step);
        cancel = function () {
            window.cancelAnimationFrame(frame);
            reject();
        };
    });
    return {
        done: donePromise,
        cancel: function () { return cancel(); },
    };
};
