您不能真正使自己的代码神奇地实现异步,因为运行Java脚本的线程一直运行到Java脚本中的完成,然后完成该事件,然后处理事件队列中的下一个事件.有时,您可以通过在计时器上以小块的形式完成自己的工作来模拟后台处理".这允许将其他操作(用户事件处理,其他计时器事件等)与您自己的执行交织在一起,但是它要求以完全不同的方式编写代码,以便可以在计时器上以小块的形式工作,而不是只是串行执行.以下是一些有用的参考资料: 最佳方法遍历数组而不阻塞UI JavaScript如何处理背景? If I have not mistaken, javascript callbacks are used with non-blocking functions. (like reading data from a file or getting data from the server).Now what makes a javascript function non-blocking? what if I want to write a non-blocking javascript function? what is the main construct which defines a non-blocking javascript function.In the following code, ready , click , slideUp are used as non-blocking functions. How did they become non-blocking functions? $(document).ready(function(){ $("button").click(function(){ $("p").slideUp(2000, function(){ $("p").slideDown(2000); }); });}); 解决方案 A non-blocking function is any function that sets up an operation, starts that operation and then uses asynchronous resources to manage finishing the operation in the background. Asynchronous resources in the browser are things like system timers, ajax calls, CSS animations, webWorkers, etc...In the code example you have in your question, both .slideUp() and .slideDown() are jQuery animations that use timers to do a little movement on each timer tick. They are asynchronous for that reason.You can also execute some types of Javascript code in a webWorker (a separate thread). webWorkers in the browser are very limited in what they can do (they can't touch the DOM at all, for example), they must be loaded from entirely separate scripts, they can't share any variables with your main javascript and they can only communicate with the main javascript via a message passing scheme. But, you can run some types of Javascript in another thread using webWorkers. Here's a summary of webWorkers on MDN.You can't literally make your own code just magically be asynchronous because a Javascript thread of execution runs until completion in Javascript and then when it's done, the next event in the event queue is processed. You can sometimes simulate "background processing" by doing pieces of your work in small chunks on a timer. This allows other operations (user event processing, other timer events, etc...) to be interwoven with your own execution, but it requires writing your code in an entirely different fashion so it can do work in small chunks on a timer, not just serial execution.Here are some useful references:Best way to iterate over an array without blocking the UIHow does JavaScript handle AJAX responses in the background? 这篇关于如何编写一个非阻塞的javascript方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-20 04:10