Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active May 6, 2024 21:26
Show Gist options
  • Save dfkaye/de63f7152f9bf2956e89cc81425ce63f to your computer and use it in GitHub Desktop.
Save dfkaye/de63f7152f9bf2956e89cc81425ce63f to your computer and use it in GitHub Desktop.
use queueMicrotask and friends to get away from IIFEs and semicolons
// 5 may 2024
// use queueMicrotask and friends to get away from IIFEs and semicolons
'use strict';
(function () {
console.group("collision")
try {
var a = "not an error"
function A () {
a = "an error"
console.warn(A.name)
}
var B = A
(function IIFE () {
console.error(IIFE.name)
})()
}
catch (e) {
console.assert(e instanceof TypeError, "e should be a TypeError")
}
finally {
console.assert(a == "an error", "a should be an error message")
}
console.groupEnd("collision")
})()
&(function () {
console.group("ampersand")
try {
var b = false
function A () {
console.error("should not see", A.name)
}
var B = A
&(function IIFE () {
console.warn("should see", IIFE.name)
})()
}
catch (e) {
b = true
console.assert(e instanceof TypeError)
}
finally {
console.assert(!(b), "b should be false")
}
console.groupEnd("ampersand")
})()
~(function (env) {
console.group("tilde with microtask")
function A (...any) {
console.log(C.name, ...any)
}
function IIFE (a, b, c) {
console.log(IIFE.name, a, b, c)
env.iifeValue = 5
}
function createMicrotask(fn, ...args) {
return () => fn(...args)
}
queueMicrotask(createMicrotask(A, 'thing'))
queueMicrotask(createMicrotask(IIFE, 'an', 'iffy', 'thing'))
queueMicrotask(function () {
console.log("read iffeValue:", env.iifeValue)
})
requestIdleCallback(createMicrotask(A, 'Idle', 'thing'))
requestAnimationFrame(createMicrotask(A, 'UI', 'thing'))
console.groupEnd("tilde with microtask")
})(globalThis)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment