16
16
17
17
package org .scalajs .macrotaskexecutor
18
18
19
- import scala .collection .mutable
20
19
import scala .concurrent .{ExecutionContext , ExecutionContextExecutor }
21
20
import scala .scalajs .js
21
+ import scala .scalajs .js .annotation ._
22
22
import scala .util .Random
23
23
import scala .util .control .NonFatal
24
24
@@ -34,10 +34,18 @@ object MacrotaskExecutor extends ExecutionContextExecutor {
34
34
def reportFailure (cause : Throwable ): Unit =
35
35
cause.printStackTrace()
36
36
37
+ @ js.native
38
+ private [this ] trait TaskMap extends js.Object {
39
+ @ JSBracketAccess
40
+ def apply (handle : Int ): Runnable
41
+ @ JSBracketAccess
42
+ def update (handle : Int , task : Runnable ): Unit
43
+ }
44
+
37
45
private [this ] val setImmediate : Runnable => Unit = {
38
46
if (js.typeOf(js.Dynamic .global.setImmediate) == Undefined ) {
39
47
var nextHandle = 1
40
- val tasksByHandle = mutable. Map [ Int , Runnable ]()
48
+ val tasksByHandle = ( new js. Object ). asInstanceOf [ TaskMap ]
41
49
var currentlyRunningATask = false
42
50
43
51
def canUsePostMessage (): Boolean = {
@@ -67,17 +75,15 @@ object MacrotaskExecutor extends ExecutionContextExecutor {
67
75
if (currentlyRunningATask) {
68
76
js.Dynamic .global.setTimeout(() => runIfPresent(handle), 0 )
69
77
} else {
70
- tasksByHandle.get(handle) match {
71
- case Some (task) =>
72
- currentlyRunningATask = true
73
- try {
74
- task.run()
75
- } finally {
76
- tasksByHandle -= handle
77
- currentlyRunningATask = false
78
- }
79
-
80
- case None =>
78
+ val task = tasksByHandle(handle)
79
+ if (! js.isUndefined(task)) {
80
+ currentlyRunningATask = true
81
+ try {
82
+ task.asInstanceOf [Runnable ].run()
83
+ } finally {
84
+ js.special.delete(tasksByHandle, handle)
85
+ currentlyRunningATask = false
86
+ }
81
87
}
82
88
}
83
89
@@ -129,7 +135,7 @@ object MacrotaskExecutor extends ExecutionContextExecutor {
129
135
val handle = nextHandle
130
136
nextHandle += 1
131
137
132
- tasksByHandle += (handle -> k)
138
+ tasksByHandle(handle) = k
133
139
js.Dynamic .global.postMessage(messagePrefix + handle, " *" )
134
140
()
135
141
}
@@ -144,7 +150,7 @@ object MacrotaskExecutor extends ExecutionContextExecutor {
144
150
val handle = nextHandle
145
151
nextHandle += 1
146
152
147
- tasksByHandle += (handle -> k)
153
+ tasksByHandle(handle) = k
148
154
channel.port2.postMessage(handle)
149
155
()
150
156
}
0 commit comments