Delay between repeated AJAX call to a web method

I have a ASP.Net web app with jquery implemented on the client side. within a while loop, the client side jquery script makes an asynchronous call to a web method in the server side code. The call returns the status of a long running server side task which jquery uses to update the user. The goal is to have jquery repeatedly call the server until the status is complete, once done it breaks out of the while loop and notifies the user thatthe task is complete. My problem is that the below code runs in a while loop, but I want to make it delay or sleep between each call in order to prevent overwhelming the server with status requests. I tried calling setTimeout in the code below, but it only works with the initial ajax call, every subsequent call occurs back to back. Is there a way to efficiently delay each subsequent call to the server? Is this the most efficient way to achieve the kind of behavior I'm describing? Ideally I'd like a 2-5 second delay between each call. I have the following code Client Jquery: var alertTimerId; $('input[name=btnStatus]').click(function () { var result = false; //Loop while server reports task complete is true while (!result) { alertTimerId = setTimeout(function () { $.ajax({ type: "POST", url: "Default.aspx/GetStatus", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", async: true, success: function (msg) { if(msg.d != false) result = msg.d; }, error: function (xhr, ajaxOptions, thrownError) { alert('AJAX failure'); } }); }, 2000); if (count > 0) { count--; } } }); Server Side ASP [System.Web.Services.WebMethod] public static bool GetStatus() { return result; }

以上就是Delay between repeated AJAX call to a web method的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准