-
Notifications
You must be signed in to change notification settings - Fork 221
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Actually add in the setImmediate module.
- Loading branch information
John Vilk
committed
Mar 19, 2017
1 parent
052139a
commit 424547a
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
import global from '../core/global'; | ||
|
||
let bfsSetImmediate: (cb: Function) => any; | ||
if (typeof(setImmediate) !== "undefined") { | ||
bfsSetImmediate = setImmediate; | ||
} else { | ||
const gScope = global; | ||
const timeouts: (() => void)[] = []; | ||
const messageName = "zero-timeout-message"; | ||
const canUsePostMessage = function() { | ||
if (typeof gScope.importScripts !== 'undefined' || !gScope.postMessage) { | ||
return false; | ||
} | ||
let postMessageIsAsync = true; | ||
const oldOnMessage = gScope.onmessage; | ||
gScope.onmessage = function() { | ||
postMessageIsAsync = false; | ||
}; | ||
gScope.postMessage('', '*'); | ||
gScope.onmessage = oldOnMessage; | ||
return postMessageIsAsync; | ||
}; | ||
if (canUsePostMessage()) { | ||
bfsSetImmediate = function(fn: () => void) { | ||
timeouts.push(fn); | ||
gScope.postMessage(messageName, "*"); | ||
}; | ||
const handleMessage = function(event: MessageEvent) { | ||
if (event.source === self && event.data === messageName) { | ||
if (event.stopPropagation) { | ||
event.stopPropagation(); | ||
} else { | ||
event.cancelBubble = true; | ||
} | ||
if (timeouts.length > 0) { | ||
const fn = timeouts.shift()!; | ||
return fn(); | ||
} | ||
} | ||
}; | ||
if (gScope.addEventListener) { | ||
gScope.addEventListener('message', handleMessage, true); | ||
} else { | ||
gScope.attachEvent('onmessage', handleMessage); | ||
} | ||
} else if (gScope.MessageChannel) { | ||
// WebWorker MessageChannel | ||
const channel = new gScope.MessageChannel(); | ||
channel.port1.onmessage = (event: any) => { | ||
if (timeouts.length > 0) { | ||
return timeouts.shift()!(); | ||
} | ||
}; | ||
bfsSetImmediate = (fn: () => void) => { | ||
timeouts.push(fn); | ||
channel.port2.postMessage(''); | ||
}; | ||
} else { | ||
bfsSetImmediate = function(fn: () => void) { | ||
return setTimeout(fn, 0); | ||
}; | ||
} | ||
} | ||
|
||
export default bfsSetImmediate; |