Skip to content

Commit 33fea6e

Browse files
committed
lib: don't penalize setInterval() common case
The common case is where setInterval() is called with two arguments, the callback and the timeout. Specifying optional arguments in the parameter list forces common case calls to go through an arguments adaptor stack frame. PR-URL: #1221 Reviewed-By: Trevor Norris <[email protected]>
1 parent 31da975 commit 33fea6e

File tree

1 file changed

+28
-30
lines changed

1 file changed

+28
-30
lines changed

lib/timers.js

+28-30
Original file line numberDiff line numberDiff line change
@@ -229,52 +229,50 @@ exports.clearTimeout = function(timer) {
229229
};
230230

231231

232-
exports.setInterval = function(callback, repeat, arg1, arg2, arg3) {
232+
exports.setInterval = function(callback, repeat) {
233233
repeat *= 1; // coalesce to number or NaN
234234

235235
if (!(repeat >= 1 && repeat <= TIMEOUT_MAX)) {
236236
repeat = 1; // schedule on next tick, follows browser behaviour
237237
}
238238

239-
var args, i;
240239
var timer = new Timeout(repeat);
241-
var len = arguments.length - 2;
242-
timer._onTimeout = wrapper;
243-
timer._repeat = true;
244-
// Initialize args once for repeated invocation of slow case below
245-
if (len > 3) {
246-
args = new Array(len);
247-
for (i = 0; i < len; i++)
248-
args[i] = arguments[i + 2];
240+
var length = arguments.length;
241+
var ontimeout = callback;
242+
switch (length) {
243+
case 0:
244+
case 1:
245+
case 2:
246+
break;
247+
case 3:
248+
ontimeout = callback.bind(timer, arguments[2]);
249+
break;
250+
case 4:
251+
ontimeout = callback.bind(timer, arguments[2], arguments[3]);
252+
break;
253+
case 5:
254+
ontimeout =
255+
callback.bind(timer, arguments[2], arguments[3], arguments[4]);
256+
break;
257+
default:
258+
var args = new Array(length - 2);
259+
for (var i = 2; i < length; i += 1)
260+
args[i - 2] = arguments[i];
261+
ontimeout = callback.apply.bind(callback, timer, args);
262+
break;
249263
}
264+
timer._onTimeout = wrapper;
265+
timer._repeat = ontimeout;
250266

251267
if (process.domain) timer.domain = process.domain;
252268
exports.active(timer);
253269

254270
return timer;
255271

256272
function wrapper() {
257-
switch (len) {
258-
// fast cases
259-
case 0:
260-
callback.call(this);
261-
break;
262-
case 1:
263-
callback.call(this, arg1);
264-
break;
265-
case 2:
266-
callback.call(this, arg1, arg2);
267-
break;
268-
case 3:
269-
callback.call(this, arg1, arg2, arg3);
270-
break;
271-
// slow case
272-
default:
273-
callback.apply(this, args);
274-
break;
275-
}
273+
timer._repeat.call(this);
276274
// If callback called clearInterval().
277-
if (timer._repeat === false) return;
275+
if (timer._repeat === null) return;
278276
// If timer is unref'd (or was - it's permanently removed from the list.)
279277
if (this._handle) {
280278
this._handle.start(repeat, 0);

0 commit comments

Comments
 (0)