|
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/. */ |
|
4 |
|
5 "use strict"; |
|
6 |
|
7 /** |
|
8 * JS module implementation of nsIDOMJSWindow.setTimeout and clearTimeout. |
|
9 */ |
|
10 |
|
11 this.EXPORTED_SYMBOLS = ["setTimeout", "clearTimeout"]; |
|
12 |
|
13 const Cc = Components.classes; |
|
14 const Ci = Components.interfaces; |
|
15 const Cu = Components.utils; |
|
16 |
|
17 Cu.import("resource://gre/modules/XPCOMUtils.jsm"); |
|
18 |
|
19 // This gives us >=2^30 unique timer IDs, enough for 1 per ms for 12.4 days. |
|
20 let gNextTimeoutId = 1; // setTimeout must return a positive integer |
|
21 |
|
22 let gTimeoutTable = new Map(); // int -> nsITimer |
|
23 |
|
24 this.setTimeout = function setTimeout(aCallback, aMilliseconds) { |
|
25 let id = gNextTimeoutId++; |
|
26 let args = Array.slice(arguments, 2); |
|
27 let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); |
|
28 timer.initWithCallback(function setTimeout_timer() { |
|
29 gTimeoutTable.delete(id); |
|
30 aCallback.apply(null, args); |
|
31 }, aMilliseconds, timer.TYPE_ONE_SHOT); |
|
32 |
|
33 gTimeoutTable.set(id, timer); |
|
34 return id; |
|
35 } |
|
36 |
|
37 this.clearTimeout = function clearTimeout(aId) { |
|
38 if (gTimeoutTable.has(aId)) { |
|
39 gTimeoutTable.get(aId).cancel(); |
|
40 gTimeoutTable.delete(aId); |
|
41 } |
|
42 } |