Jump to content

jQuery $.post every second until response is not "1"


Recommended Posts

I have a process that runs every 30 seconds and i want my script to check if it is finished. this way my user doesn't have to wait an arbitrary 30 seconds if the request is submitted closer to the 30 second mark (5 seconds to process instead of the max 30).

I tried a while loop and sending $.post within it but from my console logging it doesn't appear to process the while loop as intended

var iii = 1;
while(iii < 30){
  console.log("Checking rcon queue for " + characterID + " (" + iii + ")");
  //Code to wait 1 second before continuing.
  var start = new Date().getTime();
  var end = start;
  while(end < start + 1000) {
    end = new Date().getTime();
  //Code to $.post to check the the queue is cleared
  $.post('scripts/rcon_queue.php', {cID: characterID}, function(response){
    if(response == "1"){
      console.log("Queue is not cleared.");
    } else {
      console.log("Queue is clear.");
      iii = 30;
console.log("Loading info for character: " + characterID);

Now i would expect this to end the while loop response is anything but "1". Which happened after 7 attempts in my most recent test.

But this is not happening:


Edited by dzhax
title update
Link to comment
Share on other sites

When you use a while loop like that you cause the whole browser to freeze until all the code is finished executing. The correct way to do this is to use setTimeout() or setInterval() to send requests when needed.

var characterID = "Something";
var numRequests = 30;
var interval = setInterval(sendRequest, 1000);
var sending = false;

function sendRequest() {
  if(!sending) { // Make sure no more than one request is happening at the same time
    sending = true;
    $.post('scripts/rcon_queue.php', {cID: characterID}, handleResponse);

    if(numRequests <= 0) {
      // If we've sent 30 requests then stop sending requests
      interval = 0;

function handleRespose(response) {
  sending = false;
  if(response == "1"){
    console.log("Queue is not cleared.");
  } else {
    console.log("Queue is clear.");
    if(interval > 0) clearInterval(interval);


  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Create New...