Skip to content

Commit

Permalink
avoid using the cached timeouts unless neccisary
Browse files Browse the repository at this point in the history
  • Loading branch information
calvinmetcalf committed Jul 29, 2016
1 parent 331de4d commit ce3bd6f
Showing 1 changed file with 29 additions and 16 deletions.
45 changes: 29 additions & 16 deletions browser.js
@@ -1,5 +1,4 @@
// shim for using process in browser

var process = module.exports = {};

// cached from whatever global is present so that test runners that stub it
Expand All @@ -11,21 +10,35 @@ var cachedSetTimeout;
var cachedClearTimeout;

(function () {
try {
cachedSetTimeout = setTimeout;
} catch (e) {
cachedSetTimeout = function () {
throw new Error('setTimeout is not defined');
try {
cachedSetTimeout = setTimeout;
} catch (e) {
cachedSetTimeout = function () {
throw new Error('setTimeout is not defined');
}
}
}
try {
cachedClearTimeout = clearTimeout;
} catch (e) {
cachedClearTimeout = function () {
throw new Error('clearTimeout is not defined');
try {
cachedClearTimeout = clearTimeout;
} catch (e) {
cachedClearTimeout = function () {
throw new Error('clearTimeout is not defined');
}
}
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
return setTimeout(fun, 0);
} else {
return cachedSetTimeout.call(null, fun, 0);
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
clearTimeout(marker);
} else {
cachedClearTimeout.call(null, marker);
}
}
var queue = [];
var draining = false;
var currentQueue;
Expand All @@ -50,7 +63,7 @@ function drainQueue() {
if (draining) {
return;
}
var timeout = cachedSetTimeout.call(null, cleanUpNextTick);
var timeout = runTimeout(cleanUpNextTick);
draining = true;

var len = queue.length;
Expand All @@ -67,7 +80,7 @@ function drainQueue() {
}
currentQueue = null;
draining = false;
cachedClearTimeout.call(null, timeout);
runClearTimeout(timeout);
}

process.nextTick = function (fun) {
Expand All @@ -79,7 +92,7 @@ process.nextTick = function (fun) {
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
cachedSetTimeout.call(null, drainQueue, 0);
runTimeout(drainQueue);
}
};

Expand Down

0 comments on commit ce3bd6f

Please sign in to comment.