Understanding the event loop in JavaScript
You probably already know that JavaScript is a single-threaded programming language. This means that JavaScript runs on a single main thread in a web browser or Node.js. Running on a single main thread means running only one piece of JavaScript code at a time.
The event loop in JavaScript plays an important role in determining how code is executed on the main thread. The event loop is responsible for things like the execution of code and the collection and processing of events. It also handles the execution of any queued subtasks.
In this tutorial, you will learn the basics of event loops in JavaScript.
How the event loop works
In order to understand how the event loop works, you need to understand three important terms.
Stack
The call stack is simply a stack of function calls that tracks the execution context of a function. The stack follows the last-in-first-out (LIFO) principle, which means that the most recently called function will be the first to be executed.
queue
A queue contains a series of tasks executed by JavaScript. Tasks in this queue may cause functions to be called, which are then placed on the stack. Processing of the queue begins only when the stack is empty. Items in the queue follow a first-in, first-out (FIFO) principle. This means that the oldest tasks will be completed first.
heap
The heap is basically a large area of memory where objects are stored and allocated. Its main purpose is to store data that may be used by functions on the stack.
Basically, JavaScript is single-threaded and executes one function at a time. This single function is placed on the stack. The function can also contain other nested functions, which will be placed higher in the stack. The stack follows the LIFO principle, so the most recently called nested function will be executed first.
Asynchronous tasks such as API requests or timers will be added to the queue for later execution. The JavaScript engine starts executing tasks in the queue when it is idle.
Consider the following example:
function helloWorld() { console.log("Hello, World!"); } function helloPerson(name) { console.log(`Hello, ${name}!`); } function helloTeam() { console.log("Hello, Team!"); helloPerson("Monty"); } function byeWorld() { console.log("Bye, World!"); } helloWorld(); helloTeam(); byeWorld(); /* Outputs: Hello, World! Hello, Team! Hello, Monty! Bye, World! */
Let's see what the stack and queue would look like if we ran the code above.
Call the helloWorld()
function and put it on the stack. It logs that Hello, World! has completed its execution, so it is taken off the stack. Next the helloTeam()
function is called and placed on the stack. During execution, we log Hello, Team! and call helloPerson()
. The execution of helloTeam()
has not finished yet, so it stays on the stack while helloPerson()
is placed on top of it.
The last-in-first-out principle stipulates that helloPerson()
is executed now. This will log Hello, Monty! to the console, thus completing its execution, and helloPerson()
will be popped off the stack. After that, the helloTeam()
function will pop off the stack, and we finally reach byeWorld()
. It will record Goodbye, world! and then disappear from the stack.
The queue is always empty.
Now, consider a slight variation of the above code:
function helloWorld() { console.log("Hello, World!"); } function helloPerson(name) { console.log(`Hello, ${name}!`); } function helloTeam() { console.log("Hello, Team!"); setTimeout(() => { helloPerson("Monty"); }, 0); } function byeWorld() { console.log("Bye, World!"); } helloWorld(); helloTeam(); byeWorld(); /* Outputs: Hello, World! Hello, Team! Bye, World! Hello, Monty! */
The only change we made here is to use setTimeout()
. However, the timeout has been set to zero. Therefore, we expect Hello, Monty! to be output before Bye, World!. If you understand how the event loop works, you'll understand why this doesn't happen. < /p>
When helloTeam()
is pushed onto the stack, the setTimeout()
method is encountered. However, the call to helloPerson()
in setTimeout()
will be put into the queue and will be executed once there are no synchronization tasks to be executed.
Once the call to byeWorld()
completes, the event loop checks the queue for any pending tasks and finds a call to helloPerson()
. At this point, it executes the function and logs Hello, Monty! to the console.
This indicates that the timeout duration you provide to setTimeout()
is not a guaranteed time for the callback to execute. This is the minimum time for the callback to be executed.
Keep our web pages responsive
An interesting feature of JavaScript is that it runs a function until it completes. This means that as long as the function is on the stack, the event loop cannot process any other tasks in the queue or execute other functions.
This may cause the web page to "hang" because it is unable to perform other operations, such as processing user input or making DOM-related changes. Consider the following example, where we find the number of prime numbers in a given range:
function isPrime(num) { if (num <= 1) { return false; } for (let i = 2; i <= Math.sqrt(num); i++) { if (num % i === 0) { return false; } } return true; } function listPrimesInRange(start, end) { const primes = []; for (let num = start; num <= end; num++) { if (isPrime(num)) { primes.push(num); } } return primes; }
In our listPrimesInRange()
function, we iterate over the numbers from start
to end
. For each number, we call the isPrime()
function to see if it is prime. isPrime()
The function itself has a for
loop that goes from 2
to Math.sqrt(num)
to determine if the number is Prime number.
查找给定范围内的所有素数可能需要一段时间,具体取决于您使用的值。当浏览器进行此计算时,它无法执行任何其他操作。这是因为 listPrimesInRange()
函数将保留在堆栈中,浏览器将无法执行队列中的任何其他任务。
现在,看一下以下函数:
function listPrimesInRangeResponsively(start) { let next = start + 100,000; if (next > end) { next = end; } for (let num = start; num <= next; num++) { if (isPrime(num)) { primeNumbers.push(num); } if (num == next) { percentage = ((num - begin) * 100) / (end - begin); percentage = Math.floor(percentage); progress.innerText = `Progress ${percentage}%`; if (num != end) { setTimeout(() => { listPrimesInRangeResponsively(next + 1); }); } } if (num == end) { percentage = ((num - begin) * 100) / (end - begin); percentage = Math.floor(percentage); progress.innerText = `Progress ${percentage}%`; heading.innerText = `${primeNumbers.length - 1} Primes Found!`; console.log(primeNumbers); return primeNumbers; } } }
这一次,我们的函数仅在批量处理范围时尝试查找素数。它通过遍历所有数字但一次仅处理其中的 100,000 个来实现这一点。之后,它使用 setTimeout()
触发对同一函数的下一次调用。
setTimeout()
被调用而没有指定延迟时,它会立即将回调函数添加到事件队列中。
下一个调用将被放入队列中,暂时清空堆栈以处理任何其他任务。之后,JavaScript 引擎开始在下一批 100,000 个数字中查找素数。
尝试单击此页面上的计算(卡住)按钮,您可能会收到一条消息,指出该网页正在减慢您的浏览器速度,并建议您停止该脚本。 p>
另一方面,单击计算(响应式)按钮仍将使网页保持响应式。
最终想法
在本教程中,我们了解了 JavaScript 中的事件循环以及它如何有效地执行同步和异步代码。事件循环使用队列来跟踪它必须执行的任务。
由于 JavaScript 不断执行函数直至完成,因此进行大量计算有时会“挂起”浏览器窗口。根据我们对事件循环的理解,我们可以重写我们的函数,以便它们批量进行计算。这允许浏览器保持窗口对用户的响应。它还使我们能够定期向用户更新我们在计算中取得的进展。
The above is the detailed content of Understanding the event loop in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo(); function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

Are you looking for ways to automate your WordPress website and social media accounts? With automation, you will be able to automatically share your WordPress blog posts or updates on Facebook, Twitter, LinkedIn, Instagram and more. In this article, we will show you how to easily automate WordPress and social media using IFTTT, Zapier, and Uncanny Automator. Why Automate WordPress and Social Media? Automate your WordPre

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

To build a website using WordPress hosting, you need to: select a reliable hosting provider. Buy a domain name. Set up a WordPress hosting account. Select a topic. Add pages and articles. Install the plug-in. Customize your website. Publish your website.
