1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 * JS module implementation of setTimeout and clearTimeout.
9 // This gives us >=2^30 unique timer IDs, enough for 1 per ms for 12.4 days.
10 var gNextId = 1; // setTimeout and setInterval must return a positive integer
12 var gTimerTable = new Map(); // int -> nsITimer or idleCallback
14 // Don't generate this for every timer.
15 var setTimeout_timerCallbackQI = ChromeUtils.generateQI([
20 function _setTimeoutOrIsInterval(
27 if (typeof aCallback !== "function") {
29 `callback is not a function in ${
30 aIsInterval ? "setInterval" : "setTimeout"
35 let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
38 timer.target = aTarget;
42 QueryInterface: setTimeout_timerCallbackQI,
47 gTimerTable.delete(id);
49 aCallback.apply(null, aArgs);
55 aIsInterval ? "setInterval" : "setTimeout"
56 }() for ${Cu.getDebugName(aCallback)}`;
60 timer.initWithCallback(
63 aIsInterval ? timer.TYPE_REPEATING_SLACK : timer.TYPE_ONE_SHOT
66 gTimerTable.set(id, timer);
70 export function setTimeout(aCallback, aMilliseconds, ...aArgs) {
71 return _setTimeoutOrIsInterval(aCallback, aMilliseconds, false, null, aArgs);
74 export function setTimeoutWithTarget(
80 return _setTimeoutOrIsInterval(
89 export function setInterval(aCallback, aMilliseconds, ...aArgs) {
90 return _setTimeoutOrIsInterval(aCallback, aMilliseconds, true, null, aArgs);
93 export function setIntervalWithTarget(
99 return _setTimeoutOrIsInterval(
108 function clear(aId) {
109 if (gTimerTable.has(aId)) {
110 gTimerTable.get(aId).cancel();
111 gTimerTable.delete(aId);
114 export var clearInterval = clear;
115 export var clearTimeout = clear;
117 export function requestIdleCallback(aCallback, aOptions) {
118 if (typeof aCallback !== "function") {
119 throw new Error("callback is not a function in requestIdleCallback");
123 let callback = (...aArgs) => {
124 if (gTimerTable.has(id)) {
125 gTimerTable.delete(id);
130 ChromeUtils.idleDispatch(callback, aOptions);
131 gTimerTable.set(id, callback);
135 export function cancelIdleCallback(aId) {
136 if (gTimerTable.has(aId)) {
137 gTimerTable.delete(aId);