Home >Web Front-end >JS Tutorial >Write 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
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.
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.
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)
分离开发者的代码执行和内部操作的时间窗口是非常重要的。混合这两种行为会导致不可预测的事情发生,并且它会需要开发者了解框架内部。我想很多前台开发者已经有过类似经历。