Framework Basics: Ajax Design (II)---integrated polling technology

Source: Internet
Author: User

Framework Basics: Ajax Design (II)---integrated polling technology

The previous article introduced the AJAX technology core approach, and cross-domain issues (as long as background support cross-domain default post can), this article explains the use of AJAX implementation of polling technology, as for the Iframe,sse server one-way push, And the WebSocket duplex channel is not currently involved .

Some concepts:

Short polling: The browser through the loop or SetTimeout method, every time back to the platform to send a request, wireless loop

Long polling: The request data is kept back and forth, but if the data changes are not detected in the background, the request will be hung off. If a data change is detected, it responds to this request change data

Distinguishing Concepts:

Long connection: At the time of HTTP data transmission, the data transmission layer is always open a TCP channel, all the request resource files are multiplexed this channel to request data, there is a time-out

Short Connection: If HTTP makes a short connection, that is, each time the browser sends the request, the TCP channel is created, and then the transfer is completed and then destroyed, repeated operation, consumes a lot

Main differences:

    1. The length of the HTTP polling, through the code layer, to the background to request data.
    2. The length of the HTTP connection, is actually the TCP protocol Transport layer is the reuse of a TCP protocol.

Main business aspects: high-timeliness applications (web-side chat systems), or applications that need to wait for a response in the background (such as payments, waiting for a response to be completed).

Key code:

1234567891011121314151617181920212223242526272829303132333435363738394041 /*    * 长轮询的实现    *   a. 业务上只需要得到服务器一次响应的轮询    *   b. 业务上需要无限次得到服务器响应的轮询    *    *   param: url   请求接口地址    *          data  请求参数    *          successEvent    成功事件处理    *          isAll           是否一直请求(例如,等待付款完成业务,只需要请求一次)    *          timeout         ajax超时时间    *          timeFrequency   每隔多少时间发送一次请求    *          error           错误事件    *          timeout         超时处理    * */   longPolling:function(url,data,successEvent,isAll,timeout,timeFrequency,errorEvent,timeoutEvent){       varajaxParam ={           time:timeout,           type:"post",           url:url,           data:data,           async:false,           success:function(date){               successEvent(data);               vartimer = setTimeout(                   function(){                       tempObj.longPolling(url,data,successEvent,isAll,error,timeoutEvent);                   },timeFrequency);               //业务需求判断,是否只需要得到一次结果               if (!isAll) clearTimeout(timer);           },           //如果走了error说明该接口有问题,没必要继续下去了           error:errorEvent,           timeout:function(){               timeoutEvent();               setTimeout(function(){                   tempObj.longPolling(url,data,successEvent,isAll,error,timeoutEvent)               },timeFrequency);           }       };       ajax.common(ajaxParam);   }

Considering the business requirements, the integration of the Isall parameter has 2 meanings

    1. The chat system will always need polling, uninterrupted data is used back to the table, so Isall = True
    2. Wait for payment business only need to get background one response whether payment succeeds, so Isall = False

A little mention of some of the problems encountered:

Problem:

1234 success:function(date){     successEvent(data);    //此处使用递归,不停递归自己     tempObj.longPolling(url,data,successEvent,isAll,error,timeoutEvent);},       

Browser error:

1234567891011121314151617181920212223242526272829 Uncaught RangeError: Maximum call stack size exceeded.    at Object.common (ajax-1.2.js:202)    at Object.longPolling (ajax-1.2.js:280)    at Object.success (ajax-1.2.js:266)    at XMLHttpRequest.xhr.onload (ajax-1.2.js:160)    at Object.common (ajax-1.2.js:202)    at Object.longPolling (ajax-1.2.js:280)    at Object.success (ajax-1.2.js:266)    at XMLHttpRequest.xhr.onload (ajax-1.2.js:160)    at Object.common (ajax-1.2.js:202)    at Object.longPolling (ajax-1.2.js:280)common @ ajax-1.2.js:202longPolling @ ajax-1.2.js:280success @ ajax-1.2.js:266xhr.onload @ ajax-1.2.js:160(anonymous) @ index.html:42(anonymous) @ index.html:43ajax-1.2.js:202 Uncaught RangeError: Maximum call stack size exceeded.    at Object.common (ajax-1.2.js:202)    at Object.longPolling (ajax-1.2.js:280)    at Object.success (ajax-1.2.js:266)    at XMLHttpRequest.xhr.onload (ajax-1.2.js:160)    at Object.common (ajax-1.2.js:202)    at Object.longPolling (ajax-1.2.js:280)    at Object.success (ajax-1.2.js:266)    at XMLHttpRequest.xhr.onload (ajax-1.2.js:160)    at Object.common (ajax-1.2.js:202)    at Object.longPolling (ajax-1.2.js:280)

English Explanation:

The maximum call stack size is exceeded.

Cause of the problem:

Description of stack overflow problem caused by too many recursive calls

Explanation of the problem:

The parameters of the function call are passed through the stack space, which consumes the thread's stack resources during the call. and recursive call, only to go to the last end of the function to exit sequentially, and not before the final end point, the occupied stack space has not been released, if the number of recursive calls too many, it may lead to the stack resources used to exceed the maximum value of the thread, resulting in a stack overflow, causing the program to exit unexpectedly. JS can call itself, where the call longpolling method, in the method constantly call themselves, resulting in GC (garbage collection) has not been released, more and more large, resulting in resources exceeding the maximum limit, the direct crash. Then cascade a layer of throwing crash information

Solution:

Use settimeout to solve the problem

Solution Explanation:

Because JavaScript is single-threaded, there is a queued processing queue, so settimeout is equivalent to having a timer that constantly plugs into a processing event to the queue every once in a while. Because of this, the equivalent of the Longpolling method is finished each time, the GC will release the resources of the method, and then execute, and then release.

Code has been integrated GitHub:https://github.com/GerryIsWarrior/ajax dot Star is my biggest encouragement, next study Ajax upload file technology (H5)

PS: For polling this technology, although usually used less, but in some special business scenarios can play a big role. In the browser, there is no complete support for the situation of H5, this is still to be considered. After all, the H5 of those websocket still need H5 compatible. Moreover, the study of this piece, to the original JS, and some of the computer's underlying technology is still very helpful, such as stack overflow, not just the front end, will also encounter. In this way, the bottom of their own more solid, for the future development of the upper layer will also have a better growth.

"Forward from http://www.cnblogs.com/GerryOfZhong/p/6135288.html"

Framework Basics: Ajax Design (II)---integrated polling technology

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.