


Browser suspended animation during ajax synchronization operation (detailed tutorial)
Below I will share with you an article that solves the problem of browser suspended animation caused by js ajax synchronization request. It has a good reference value and I hope it will be helpful to everyone.
1. The cause of the problem
#I encountered a situation when I made a request today, that is, there is a function in the user's personal center. Click the button. You can refresh the user's current points. This definitely requires the use of ajax synchronization requests. At that time, I wrote and played with three, five, and two. The approximate code is as follows:
/** * 异步当前用户积分 by zgw 20161216 * @return {[type]} [description] */ function flushIntegralSum() { //点击按钮刷新前修改按钮的文案,已经去掉点击事情,防止多次点击 $("#flushbutton").replaceWith('<a style="color:#3fb0ff;font-size:14px;" href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="flushbutton">正在刷新</a>'); $.ajax({ url:'URL', type:'post', async:false, // data:{}, success:function(json){ json = eval('('+json+')'); if(json.url){window.location.href=json.url;return;} $("#flushbutton").replaceWith('<a style="color:#3fb0ff;font-size:14px;" href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="flushFreeSum();" id="flushbutton">刷新积分</a>'); if(json.code!=1){ alert(json.msg); }else{ $("#free_sum").html(json.free_sum); } return; } }); }
I thought such a simple function was Just write it and it will be fine. However, a problem occurred during operation. When the user clicked the refresh points button, the copy was not changed to "Refreshing", but the ajax request was sent. So I checked the web page code and found that js actually changed the copy. The onclick event bound to the html element was removed and changed back to the original after the request was successful, but the copy on the page did not change. It was strange at the time. I don’t know why the html code changed but the page did not change.
2. Understand the cause of the problem
The root of the problem: I conducted a troubleshooting at that time, and finally found that it was an "async:false" problem, and replaced it with There is no problem if it is asynchronous, so why does synchronous request cause code failure?
Reason: The browser's rendering (UI) thread and js thread are mutually exclusive. When executing js time-consuming operations, page rendering will be blocked. There is no problem when we execute asynchronous ajax, but when set to a synchronous request, other actions (the code behind the ajax function, and the rendering thread) will stop. Even if my DOM operation statement is in the sentence before the request is initiated, this synchronization request will "quickly" block the UI thread without giving it time to execute. This is why the code fails.
3. Solve the problem
1. I used setTimeout to solve the problem, put the ajax code in sestTimeout and let the browser restart One thread to operate, this solves the problem, the code is as follows:
function flushIntegralSum() { //点击按钮刷新前修改按钮的文案,已经去掉点击事情,防止多次点击 $("#flushbutton").replaceWith('<a style="color:#3fb0ff;font-size:14px;" href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="flushbutton">正在刷新</a>'); setTimeout(function(){ $.ajax({ url:'URL', type:'post', async:false, // data:{}, success:function(json){ json = eval('('+json+')'); if(json.url){window.location.href=json.url;return;} $("#flushbutton").replaceWith('<a style="color:#3fb0ff;font-size:14px;" href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="flushFreeSum();" id="flushbutton">刷新积分</a>'); if(json.code!=1){ alert(json.msg); }else{ $("#free_sum").html(json.free_sum); } return; } }); },0) }
The second parameter of setTimeout is set to 0, and the browser will execute it after a set minimum time
The problem is solved here, but you can try it. If you need to pop up a gif picture when you click the button, and the picture keeps rotating, it will prompt that the picture is being updated. You will find that the picture is being updated. Although it will be displayed, the picture does not move. That is because although the synchronization request is delayed, it will still block the UI thread during its execution. This blocking is so awesome that even the gif image doesn't move and looks like a static image. The conclusion is obvious. setTimeout treats the symptoms but not the root cause. It is equivalent to making the synchronization request "slightly" asynchronous. Then it will still enter a synchronization nightmare and block the thread. This method is only suitable for simple and short operations before sending the request.
2. Use Deferred to solve
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to implement custom instructions in Vue?
How to modify the sub-component style through the parent component in vue
Related to jsonp cross-domain issues in vue-resource
How to implement asynchronous component loading in vue webpack?
Use Nginx in vue.js to solve cross-domain issues
How to achieve the maximum common substring in JavaScript
How to implement mysql transaction automatic recycling connection in Node.js
The above is the detailed content of Browser suspended animation during ajax synchronization operation (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Linux new version
SublimeText3 Linux latest version
