Explain event loop in JS Runtime with pseudocode

Created
Mar 5, 2022 05:49 AM
Tags
javascript
browser
// The if-else pattern is replaced by if-only expressions for consisitency and clarity. 

// A new JavaScript program or subprogram is executed, a initial task is created
taskQueue.enqueue(initParse())

// Event Loop
while everyTick {
	if !callstack.isEmpty() {continue}
	taskQueue.dequeue().excuteStepsByJSEngine()
	while !microTaskQueue.isEmpty() {
		microTaskQueue.dequeue().excuteStepsByJSEngine()
	}

	// Re-render process
	// requestAnimationFrame task queue will be cleaned/runned before:
	// - scripting(event callbacks, timer callbacks ...)
	// - style calculation
	// - layout
	// - paint
	maybeReRenderInBroswerEnvironment()
}

// Parse HTML and JS, find tasks
function initParse() {
	when findNewTask {
		handleTask(task)
	}
}

function handleTask(task) {
	if isSync(task) {
			callstack.push(task)
			task.excuteStepsByJSEngine()
			callstack.pop()
		} 
		
	if isAsync(task) {
		// marcotask
		if dispatchedByHost(task) {
			// note!: Mutation Observer API is a host API, but will cause a microtask
			waitForMessage((task with message) => {
				taskQueue.enqueue(task))
			})
		} 
		
		// micortask
		if dispatchedByJSEngine(task) || isQueueMicrotaskFunctionCall(task) {
			waitForMessage((task with message) => {
				microTaskQueue.enqueue(task)
			})
		}
	}
}

GitHub gist version of the above code

Refs