DEV Community

dean glükler
dean glükler

Posted on

An OOP sudocode representation of the JS event loop

class EventLoop {
    constructor() {
        this.latestRenderTime = Date.now();
        this.taskQueue = [];
        this.requestAnimQueue = [];
    }

    begin() {
        while (1) {
            this.theLoop();
        }
    }

    theLoop() {
        this.processTask();

        this.processAllMicroTasks();

        // render if it's been over 60 ms (refresh screen)
        if (Date.now() - this.latestRenderTime >= 60) {
            this.processAllRequestAnimationTasks();
            this.renderSteps();
        }
    }

    processTask() {
        // process one tasks (if exists) until completion
    }

    processAllRequestAnimationTasks() {
        // process all request animation frame callbacks that exist
        // if new requestAnimationFrame callbacks are declared, queue them for next frame
    }

    processAllMicroTasks() {
        // process all microTasks
        // if new microtasks, add them to stack and process until finished
        // this can block rendering
    }

    renderSteps() {
        // in browser land..
        // do style calculation
        // do layout render tree
        // paint pixel data
        this.latestRenderTime = Date.now();
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)