开发者

Infinite loop wait 2 second, make server call jquery

I am making a simple game with jquery and i want to make a call to asp.net web service which i know how to do, but the server call need to continue to run until i get a specific response from the server.

I will wait like 3 seconds with each loop cycle

function servercall() {
            while (true) {
                // code for clone and insert  ...
                $.ajax({
                    type: "POST",
                    url: "Server.asmx/HelloWorld",
                    data: "{'name': '" + $('#name').val() + "', 'time': '2pm'}",
                    contentTyp开发者_Go百科e: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                        AjaxSucceeded(msg);
                    },
                    error: AjaxFailed
                });
                setTimeout("nothing", 2000);
            }

        }


Use recursion with setTimeout. And be sure start the timer when you receive a response, so that you account for network delays (you don't want a bunch of requests going at the same time)...

function servercall() { 
  $.ajax({ 
    complete: function(xhr) { 
      var msg = xhr.responseText;
      if(xhr.statusCode == 200)
        AjaxSucceeded(msg); 
      else
        AjaxFailed(msg);

      setTimeout(servercall, 2000); //recursion magic
    }
  }); 
}


You want the JavaScript setTimeout() Function.


You could try either:

function serverCall() {
    // ajax code

    setTimeout("serverCall()", 2000);
}

or:

function ajaxSucceeded(msg) {
    if (isTheAnswerYouAreLookingFor) {
        // do stuff
    } else {
        setTimeout("serverCall()", 2000);
    }
}

Here is an article on setTimeout and setInterval that may help you further:
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/


Set interval is more helpful :

<script type='text/javascript'>

setInterval("servercall()", 2000);

function servercall() {

                // code for clone and insert  ...
                $.ajax({
                    type: "POST",
                    url: "Server.asmx/HelloWorld",
                    data: "{'name': '" + $('#name').val() + "', 'time': '2pm'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                        AjaxSucceeded(msg);
                    },
                    error: AjaxFailed
                });

            }

        }

</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜