search
HomeWeb Front-endJS TutorialWrite a JavaScript framework: better timing execution than setTimeout

This is the second chapter of the JavaScript framework series. In this chapter, I plan to talk about different ways of executing asynchronous code in the browser. You'll learn about the different differences between timers and event loops, such as setTimeout and Promises.

This series is about an open source client framework called NX. In this series, I mainly explain the main difficulties that I had to overcome when writing this framework. If you are interested in NX you can visit our home page.

This series contains the following chapters:

Project structure

Scheduled execution (current chapter)

Sandbox code evaluation

Introduction to data binding

Data binding and ES6 proxy

Custom elements

Customer End routing

Asynchronous code execution

You may be familiar with Promise, process.nextTick(), setTimeout(), and perhaps requestAnimationFrame(), which are ways to execute code asynchronously. They both use event loops internally, but they have some differences in precise timing.

In this chapter, I will explain the differences between them, and then show you how to implement a timing system in an advanced framework like NX. Rather than having to reinvent the wheel, we'll use the native event loop to achieve our goals.

Event loop

The event loop is not even mentioned in the ES6 specification. JavaScript itself only has tasks (Jobs) and task queues (job queues). More complex event loops are defined in the NodeJS and HTML5 specifications respectively. Since this article is for the front end, I will explain the latter in detail.

The event loop can be seen as a loop of a certain condition. It is constantly looking for new tasks to run. An iteration in this loop is called a tick. Code executed during a tick is called a task.

while (eventLoop.waitForTask()) {   
  eventLoop.processNextTask() 
}

Tasks are synchronous code that schedule other tasks in a loop. A simple way to call a new task is setTimeout(taskFn). Regardless, tasks may come from many sources, such as user events, network or DOM operations

Write a JavaScript framework: better timing execution than setTimeout

Task Queues

To make things more complicated, the event loop can have multiple task queues. There are two constraints here, events from the same task source must be in the same queue, and tasks must be processed in the order of insertion. Other than that, the browser can do whatever it wants. For example, it can decide which task queue to process next.

while (eventLoop.waitForTask()) {   
  const taskQueue = eventLoop.selectTaskQueue() 
  if (taskQueue.hasNextTask()) { 
    taskQueue.processNextTask() 
  } 
}

With this model, we cannot control the timing precisely. If you use setTimeout(), the browser may decide to run several other queues before running our queue.

Write a JavaScript framework: better timing execution than setTimeout

Microtask Queue

Fortunately, the event loop also provides a single queue called the microtask queue. When the current task ends, the microtask queue will clear the tasks in each tick.

while (eventLoop.waitForTask()) {   
  const taskQueue = eventLoop.selectTaskQueue() 
  if (taskQueue.hasNextTask()) { 
    taskQueue.processNextTask() 
  } 
  const microtaskQueue = eventLoop.microTaskQueue 
  while (microtaskQueue.hasNextMicrotask()) { 
    microtaskQueue.processNextMicrotask() 
  } 
}

The simplest way to call a microtask is Promise.resolve().then(microtaskFn). Microtasks are processed in the order of insertion, and since there is only one microtask queue, the browser does not mess up the timing.

Additionally, microtasks can schedule new microtasks, which will be inserted into the same queue and processed within the same tick.

Write a JavaScript framework: better timing execution than setTimeout

Drawing Rendering

The last step is rendering rendering scheduling. Unlike event processing and decomposition, rendering is not completed in a separate background task. It is an algorithm that can be run at the end of each loop tick.

The browser has a lot of freedom here: it may draw after each task, but it may also not draw after hundreds of tasks have been executed.

Luckily, we have requestAnimationFrame() which executes the passed function before the next draw. Our final event model looks like this:

while (eventLoop.waitForTask()) {   
  const taskQueue = eventLoop.selectTaskQueue() 
  if (taskQueue.hasNextTask()) { 
    taskQueue.processNextTask() 
  } 
  const microtaskQueue = eventLoop.microTaskQueue 
  while (microtaskQueue.hasNextMicrotask()) { 
    microtaskQueue.processNextMicrotask() 
  } 
  if (shouldRender()) { 
    applyScrollResizeAndCSS() 
    runAnimationFrames() 
    render() 
  } 
}

Now use what we know to create a timing system!

Leveraging the event loop

Like most modern frameworks, NX is based on DOM manipulation and data binding. Batch operations and asynchronous execution for better performance. For the above reasons we use Promises, MutationObservers and requestAnimationFrame().

The timer we expect is like this:

The code comes from the developer

Data binding and DOM operations are performed by NX

Developer-defined event hooks

Browser draws

Step 1

NX register objects run synchronously based on ES6 proxies and DOM changes based on MutationObserver (details in the next section). It acts as a microtask and delays its response until step 2 is executed. This delay has object conversion in Promise.resolve().then(reaction) and it will run automatically through the change observer.

Step 2

The code (task) from the developer is completed. Microtasks are registered by NX to start execution. Because they are microtasks, they are executed sequentially. Note that we are still in the same ticking loop.

步骤 3

开发者通过 requestAnimationFrame(hook) 通知 NX 运行钩子。这可能在滴答循环后发生。重要的是,钩子运行在下一次绘制之前和所有数据操作之后,并且 DOM 和 CSS 改变都已经完成。

步骤 4

浏览器绘制下一个视图。这也有可能发生在滴答循环之后,但是绝对不会发生在一个滴答的步骤 3 之前。

牢记在心里的事情

我们在原生的事件循环之上实现了一个简单而有效的定时系统。理论上讲它运行的很好,但是还是很脆弱,一个轻微的错误可能会导致很严重的 BUG。

在一个复杂的系统当中,最重要的就是建立一定的规则并在以后保持它们。在 NX 中有以下规则:

永远不用 setTimeout(fn, 0) 来进行内部操作

用相同的方法来注册微任务

微任务仅供内部操作

不要干预开发者钩子运行时间

规则 1 和 2

数据反射和 DOM 操作将按照操作顺序执行。这样只要不混合就可以很好的延迟它们的执行。混合执行会出现莫名其妙的问题。

setTimeout(fn, 0) 的行为完全不可预测。使用不同的方法注册微任务也会发生混乱。例如,下面的例子中 microtask2 不会正确地在 microtask1 之前运行。

Promise.resolve().then().then(microtask1)   
Promise.resolve().then(microtask2)

Write a JavaScript framework: better timing execution than setTimeout

分离开发者的代码执行和内部操作的时间窗口是非常重要的。混合这两种行为会导致不可预测的事情发生,并且它会需要开发者了解框架内部。我想很多前台开发者已经有过类似经历。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use