读书人

何setTimeout的ajax可以有序从

发布时间: 2012-11-22 00:16:41 作者: rapoo

何setTimeout的ajax可以有序自用

$(document).ready(function(){var FREQ = 10000 ;var repeat = true;function showFrequency(){$("#freq").html( "Page refreshes every " + FREQ/1000 + " second(s).");}function startAJAXcalls(){if(repeat){setTimeout(     function() {getXMLRacers();startAJAXcalls();}, FREQ);}}function getXMLRacers(){$.ajax({url: "finishers.xml",cache: false,dataType: "xml",success:  function(xml){$('#finishers_m').empty();$('#finishers_f').empty();$('#finishers_all').empty();$(xml).find("runner").each(function() {var info = '<li>Name: ' + $(this).find("fname").text() + ' ' + $(this).find("lname").text() + '. Time: ' + $(this).find("time").text() + '</li>';if( $(this).find("gender").text() == "m" ){$('#finishers_m').append( info );}else if ( $(this).find("gender").text() == "f" ){$('#finishers_f').append( info );}else{  }$('#finishers_all').append( info );});getTimeAjax();}});}function getTimeAjax(){$('#updatedTime').load("time.php");/*var time = "";$.ajax({url: "time.php",cache: false,success: function(data){$('#updatedTime').html(data);}});*/}$("#btnStop").click(function(){repeat = false;$("#freq").html( "Updates paused." );});$("#btnStart").click(function(){repeat = true;startAJAXcalls();showFrequency();});showFrequency();getXMLRacers();startAJAXcalls();});
?

是在HeadFirst JQuery第八章中出的,什麽其中的
startAJAXcalls可以有序自用呢?一getXMLRacers()用卡住超十秒,它能有序?

?

它面了很多:

Since we wait until the last call to our function is finished, we use the setTimeout function.

?

Self-referencing functions
A self-referencing function calls itself during its normal operations. Such functions can be particularly
useful when you need to wait for the function’s currently running operation to complete before running
it again. Combine this with a setTimeout call, and you can schedule a function to run but only keep
going if the previous call to the function was successful. Otherwise, it won’t reach the call to itself in the
code, and hence it won’t be called again.

?

其我理解主要是setTimeout中的函的用是多程,因此不阻塞主程,有一前提就是getXMLRacers()不卡住超10秒,否就出startAJAXcalls行行的局面,不能保有序了。

?

在:

FREQ=100;function startAJAXcalls(){    if(repeat){        alert("start");        setTimeout(            function() {                alert("xml racers started");                getXMLRacers();                sleep(5000);                alert("ajax calls started");                startAJAXcalls();                alert("ajax calls finished");            },                FREQ        );        alert("end");    }}   function sleep(numberMillis) {    var now = new Date();    var exitTime = now.getTime() + numberMillis;     while (true) {        now = new Date();        if (now.getTime() > exitTime)               return;    }}
?

行中些alert量都是1:1,而且alert("ajax calls finished");每次都行到,真是奇之怪哉,不同於java中的表。真如其所,self-referencing用等上次用行完后才去用,但是什麽呢?是什麽制。

?

?

读书人网 >Ajax

热点推荐