# all files / lib/utilities/Async/ Async.js

39.69% Statements 77/194
21.88% Branches 28/128
34.78% Functions 8/23
39.69% Lines 77/194

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379

    1×
    1×
    11×
    11×
    11×
    11×
    11×
    11×
    11×
    11×

    1×

    1×
    3×
    3×
    3×
    3×
    3×

    3×

    3×

    3×
    3×

    3×

    3×

    1×
    3×

    1×

    1×

    1×

    1×

    1×

    1×
    11×
    11×

    11×
    11×
    11×
    11×
    11×
    11×
    11×
    11×
    11×
    11×

    11×

    11×

    11×
    6×
    6×
    6×
    3×

    3×

    6×
    6×
    6×
    6×
    6×

    6×
    3×
    3×
    3×

    3×
    3×

    3×
    3×

    6×

    11×
    3×
    3×
    3×

    3×
    3×

    11×

    1×

    1×

    1×

    1×

    1×

     /**
     * Bugs often appear in async code when stuff gets disposed, but async operations don't get canceled.
     * This Async helper class solves these issues by tying async code to the lifetime of a disposable object.
     *
     * Usage: Anything class extending from BaseModel can access this helper via this.async. Otherwise create a
     * new instance of the class and remember to call dispose() during your code's dispose handler.
     */
    "use strict";
    var Async = (function () {
        function Async(parent, onError) {
            this._timeoutIds = null;
            this._immediateIds = null;
            this._intervalIds = null;
            this._animationFrameIds = null;
            this._isDisposed = false;
            this._parent = parent || null;
            this._onErrorHandler = onError;
            this._noop = function () { };
        }
        /**
         * Dispose function, clears all async operations.
         */
        Async.prototype.dispose = function () {
            var id;
            this._isDisposed = true;
            this._parent = null;
            // Clear timeouts.
            if (this._timeoutIds) {
                for (id in this._timeoutIds) {
                    if (this._timeoutIds.hasOwnProperty(id)) {
                        this.clearTimeout(id);
                    }
                }
                this._timeoutIds = null;
            }
            // Clear immediates.
            if (this._immediateIds) {
                for (id in this._immediateIds) {
                    if (this._immediateIds.hasOwnProperty(id)) {
                        this.clearImmediate(id);
                    }
                }
                this._immediateIds = null;
            }
            // Clear intervals.
            if (this._intervalIds) {
                for (id in this._intervalIds) {
                    if (this._intervalIds.hasOwnProperty(id)) {
                        this.clearInterval(id);
                    }
                }
                this._intervalIds = null;
            }
            // Clear animation frames.
            if (this._animationFrameIds) {
                for (id in this._animationFrameIds) {
                    if (this._animationFrameIds.hasOwnProperty(id)) {
                        this.cancelAnimationFrame(id);
                    }
                }
                this._animationFrameIds = null;
            }
        };
        /**
         * SetTimeout override, which will auto cancel the timeout during dispose.
         * @param callback Callback to execute.
         * @param duration Duration in milliseconds.
         * @return The setTimeout id.
         */
        Async.prototype.setTimeout = function (callback, duration) {
            var _this = this;
            var timeoutId = 0;
            Eif (!this._isDisposed) {
                Eif (!this._timeoutIds) {
                    this._timeoutIds = {};
                }
                /* tslint:disable:ban-native-functions */
                timeoutId = setTimeout(function () {
                    // Time to execute the timeout, enqueue it as a foreground task to be executed.
                    try {
                        // Now delete the record and call the callback.
                        delete _this._timeoutIds[timeoutId];
                        callback.apply(_this._parent);
                    }
                    catch (e) {
                        if (_this._onErrorHandler) {
                            _this._onErrorHandler(e);
                        }
                    }
                }, duration);
                /* tslint:enable:ban-native-functions */
                this._timeoutIds[timeoutId] = true;
            }
            return timeoutId;
        };
        /**
         * Clears the timeout.
         * @param id Id to cancel.
         */
        Async.prototype.clearTimeout = function (id) {
            Iif (this._timeoutIds && this._timeoutIds[id]) {
                /* tslint:disable:ban-native-functions */
                clearTimeout(id);
                delete this._timeoutIds[id];
            }
        };
        /**
         * SetImmediate override, which will auto cancel the immediate during dispose.
         * @param callback Callback to execute.
         * @return The setTimeout id.
         */
        Async.prototype.setImmediate = function (callback) {
            var _this = this;
            var immediateId = 0;
            if (!this._isDisposed) {
                if (!this._immediateIds) {
                    this._immediateIds = {};
                }
                /* tslint:disable:ban-native-functions */
                var setImmediateCallback = function () {
                    // Time to execute the timeout, enqueue it as a foreground task to be executed.
                    try {
                        // Now delete the record and call the callback.
                        delete _this._immediateIds[immediateId];
                        callback.apply(_this._parent);
                    }
                    catch (e) {
                        _this._logError(e);
                    }
                };
                immediateId = window.setImmediate ? window.setImmediate(setImmediateCallback) : window.setTimeout(setImmediateCallback, 0);
                /* tslint:enable:ban-native-functions */
                this._immediateIds[immediateId] = true;
            }
            return immediateId;
        };
        /**
         * Clears the immediate.
         * @param id Id to cancel.
         */
        Async.prototype.clearImmediate = function (id) {
            if (this._immediateIds && this._immediateIds[id]) {
                /* tslint:disable:ban-native-functions */
                window.clearImmediate ? window.clearImmediate(id) : window.clearTimeout(id);
                delete this._immediateIds[id];
            }
        };
        /**
         * SetInterval override, which will auto cancel the timeout during dispose.
         * @param callback Callback to execute.
         * @param duration Duration in milliseconds.
         * @return The setTimeout id.
         */
        Async.prototype.setInterval = function (callback, duration) {
            var _this = this;
            var intervalId = 0;
            if (!this._isDisposed) {
                if (!this._intervalIds) {
                    this._intervalIds = {};
                }
                /* tslint:disable:ban-native-functions */
                intervalId = setInterval(function () {
                    // Time to execute the interval callback, enqueue it as a foreground task to be executed.
                    try {
                        callback.apply(_this._parent);
                    }
                    catch (e) {
                        _this._logError(e);
                    }
                }, duration);
                /* tslint:enable:ban-native-functions */
                this._intervalIds[intervalId] = true;
            }
            return intervalId;
        };
        /**
         * Clears the interval.
         * @param id Id to cancel.
         */
        Async.prototype.clearInterval = function (id) {
            if (this._intervalIds && this._intervalIds[id]) {
                /* tslint:disable:ban-native-functions */
                clearInterval(id);
                delete this._intervalIds[id];
            }
        };
        /**
         * Creates a function that, when executed, will only call the func function at most once per
         * every wait milliseconds. Provide an options object to indicate that func should be invoked
         * on the leading and/or trailing edge of the wait timeout. Subsequent calls to the throttled
         * function will return the result of the last func call.
         *
         * Note: If leading and trailing options are true func will be called on the trailing edge of
         * the timeout only if the the throttled function is invoked more than once during the wait timeout.
         *
         * @param func The function to throttle.
         * @param wait The number of milliseconds to throttle executions to. Defaults to 0.
         * @param options The options object.
         * @param options.leading Specify execution on the leading edge of the timeout.
         * @param options.trailing Specify execution on the trailing edge of the timeout.
         * @return The new throttled function.
         */
        Async.prototype.throttle = function (func, wait, options) {
            var _this = this;
            if (this._isDisposed) {
                return this._noop;
            }
            var waitMS = wait || 0;
            var leading = true;
            var trailing = true;
            var lastExecuteTime = 0;
            var lastResult;
            var lastArgs;
            var timeoutId = null;
            if (options && typeof (options.leading) === 'boolean') {
                leading = options.leading;
            }
            if (options && typeof (options.trailing) === 'boolean') {
                trailing = options.trailing;
            }
            var callback = function (userCall) {
                var now = (new Date).getTime();
                var delta = now - lastExecuteTime;
                var waitLength = leading ? waitMS - delta : waitMS;
                if (delta >= waitMS && (!userCall || leading)) {
                    lastExecuteTime = now;
                    if (timeoutId) {
                        _this.clearTimeout(timeoutId);
                        timeoutId = null;
                    }
                    lastResult = func.apply(_this._parent, lastArgs);
                }
                else if (timeoutId === null && trailing) {
                    timeoutId = _this.setTimeout(callback, waitLength);
                }
                return lastResult;
            };
            var resultFunction = function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i - 0] = arguments[_i];
                }
                lastArgs = args;
                return callback(true);
            };
            return resultFunction;
        };
        /**
         * Creates a function that will delay the execution of func until after wait milliseconds have
         * elapsed since the last time it was invoked. Provide an options object to indicate that func
         * should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls
         * to the debounced function will return the result of the last func call.
         *
         * Note: If leading and trailing options are true func will be called on the trailing edge of
         * the timeout only if the the debounced function is invoked more than once during the wait
         * timeout.
         *
         * @param func The function to debounce.
         * @param wait The number of milliseconds to delay.
         * @param options The options object.
         * @param options.leading Specify execution on the leading edge of the timeout.
         * @param options.maxWait The maximum time func is allowed to be delayed before it's called.
         * @param options.trailing Specify execution on the trailing edge of the timeout.
         * @return The new debounced function.
         */
        Async.prototype.debounce = function (func, wait, options) {
            var _this = this;
            Iif (this._isDisposed) {
                return this._noop;
            }
            var waitMS = wait || 0;
            var leading = false;
            var trailing = true;
            var maxWait = null;
            var lastCallTime = 0;
            var lastExecuteTime = (new Date).getTime();
            var lastResult;
            var lastArgs;
            var timeoutId = null;
            Iif (options && typeof (options.leading) === 'boolean') {
                leading = options.leading;
            }
            Iif (options && typeof (options.trailing) === 'boolean') {
                trailing = options.trailing;
            }
            Iif (options && typeof (options.maxWait) === 'number' && !isNaN(options.maxWait)) {
                maxWait = options.maxWait;
            }
            var callback = function (userCall) {
                var now = (new Date).getTime();
                var executeImmediately = false;
                if (userCall) {
                    Iif (leading && now - lastCallTime >= waitMS) {
                        executeImmediately = true;
                    }
                    lastCallTime = now;
                }
                var delta = now - lastCallTime;
                var waitLength = waitMS - delta;
                var maxWaitDelta = now - lastExecuteTime;
                var maxWaitExpired = false;
                Iif (maxWait !== null) {
                    // maxWait only matters when there is a pending callback
                    if (maxWaitDelta >= maxWait && timeoutId) {
                        maxWaitExpired = true;
                    }
                    else {
                        waitLength = Math.min(waitLength, maxWait - maxWaitDelta);
                    }
                }
                if (delta >= waitMS || maxWaitExpired || executeImmediately) {
                    Eif (timeoutId) {
                        _this.clearTimeout(timeoutId);
                        timeoutId = null;
                    }
                    lastExecuteTime = now;
                    lastResult = func.apply(_this._parent, lastArgs);
                }
                else Eif ((timeoutId === null || !userCall) && trailing) {
                    timeoutId = _this.setTimeout(callback, waitLength);
                }
                return lastResult;
            };
            var resultFunction = function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i - 0] = arguments[_i];
                }
                lastArgs = args;
                return callback(true);
            };
            return resultFunction;
        };
        Async.prototype.requestAnimationFrame = function (callback) {
            var _this = this;
            var animationFrameId = 0;
            if (!this._isDisposed) {
                if (!this._animationFrameIds) {
                    this._animationFrameIds = {};
                }
                /* tslint:disable:ban-native-functions */
                var animationFrameCallback = function () {
                    try {
                        // Now delete the record and call the callback.
                        delete _this._animationFrameIds[animationFrameId];
                        callback.apply(_this._parent);
                    }
                    catch (e) {
                        _this._logError(e);
                    }
                };
                animationFrameId = window.requestAnimationFrame ?
                    window.requestAnimationFrame(animationFrameCallback) :
                    window.setTimeout(animationFrameCallback, 0);
                /* tslint:enable:ban-native-functions */
                this._animationFrameIds[animationFrameId] = true;
            }
            return animationFrameId;
        };
        Async.prototype.cancelAnimationFrame = function (id) {
            if (this._animationFrameIds && this._animationFrameIds[id]) {
                /* tslint:disable:ban-native-functions */
                window.cancelAnimationFrame ? window.cancelAnimationFrame(id) : window.clearTimeout(id);
                /* tslint:enable:ban-native-functions */
                delete this._animationFrameIds[id];
            }
        };
        Async.prototype._logError = function (e) {
            if (this._onErrorHandler) {
                this._onErrorHandler(e);
            }
        };
        return Async;
    }());
    exports.Async = Async;

    //# sourceMappingURL=Async.js.map