There are still some shortcomings in a previously written Ajax random text refresh. At that time, the following algorithm was used to achieve the value from the server for a period of time:
Var secs = 300; // number of seconds for countdown function doUpdate (num) {if (num % 3 = 0) {saveUserInfo () ;}} for (var I = secs; i> = 0; I --) {window. setTimeout ("doUpdate (" + I + ")", (secs-I) * 1000 );}
The countdown principle is used. Every time the variable secs can divide 3, The saveUserInfo () function is executed to obtain the value from the server every three seconds. However, this is not efficient first, because a logical judgment is required each time. Secondly, the program is unknown.
This function is now implemented using nested loops.
Function saveUserInfo () {// obtain and accept the returned information layer var cdown = document. getElementById ("cdown"); // alert (cdown); // URL of the received form var url = "word. php "; var ajax = false; // start to initialize the XMLHttpRequest object if (window. XMLHttpRequest) {// Mozilla Browser ajax = new XMLHttpRequest (); if (ajax. overrideMimeType) {// sets the MiME type ajax. overrideMimeType ("text/xml") ;}} else if (window. activeXObject) {// IE browser try {ajax = new ActiveXObject (" Msxml2.XMLHTTP ");} catch (e) {try {ajax = new ActiveXObject (" Microsoft. XMLHTTP ");} catch (e) {}} if (! Ajax) {// An error occurred while creating the object instance window. alert ("the XMLHttpRequest object instance cannot be created. "); return false;} // open the connection ajax in Post mode. open ("GET", url, true); // defines the HTTP header information of the transmitted file // ajax. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); ajax. setRequestHeader ("If-Modified-Since", "0"); // send POST data ajax. send (null); // get the execution status ajax. onreadystatechange = function () {// if the execution status is successful, write the returned information to the specified layer if (ajax. readyState = 4 & ajax. status = 200) {cdown. innerHTML = ajax. responseText ;}} function doUpdate () {saveUserInfo (); window. setTimeout ("doUpdate ()", 8000);} doUpdate ();
In fact, the most important part is the following code:
function doUpdate() { saveUserInfo();window.setTimeout("doUpdate()", 8000);} doUpdate();
First, use doUpdate () to start function execution. When doUpdate () is executed, saveUserInfo () is called to obtain the value from the server, and then call itself 8 seconds later, as long as the page exists, the value will always go through. A Recursion greatly simplifies the program.