this is just a code piece from larger code. check what could be wrong here??? specifically timeouts used for queuing a backend. maybe some weird stuff is happening in timings?: ```  const headers = response.headers;
  const estimatedTimeString = headers.get('estimated_time');
  estimatedTime = parseFloat(estimatedTimeString) * 1000;

  // Handle HTTP 429 errors by throwing an error with the response object
  if (response.status === 429) {
    const error = new Error('Backend error');
    error.response = response;
    throw error;
  }

  const result = await response.blob();
  return result;
}

let modelToken = modelTokens[currentTokenIndex];
let tokenSwitched = false;
let lastTokenSwitchTime = null;

const minDelay = 2000;
const maxDelay = 30000;
const jitterRange = 1000;
const circuitBreakerThreshold = 20;
const circuitBreakerResetTime = 10000;

let retryDelay = minDelay;

async function executeQuery(data, modelToken, currentTokenIndex) {
  try {
    // Send the request with the current model token
    const result = await query(data, modelToken);

    // Reset the retry delay and current retries count
    retryDelay = minDelay;
    currentRetries = 0;

    // Check if the result contains an image or an error
    if (result.type === 'image/jpeg') {
      return result;
    } else {
      throw new Error('Backend error');
    }
  } catch (error) {
    // Check if the error is an HTTP 429 error
    if (error.message === 'Backend error' && error.response && error.response.status === 429) {
      console.log('Received HTTP 429 error');

      // Check if the token has already been switched for this particular error
      if (!tokenSwitched) {
        console.log('Switching to another model token');
        currentRetries = 0;
        lastTokenSwitchTime = Date.now();
        tokenSwitched = true;

        // Increment the current token index and get the next model token
        currentTokenIndex = (currentTokenIndex + 1) % modelTokens.length;
        modelToken = modelTokens[currentTokenIndex];
      } else {
        // Check if the timeout duration for token switching has passed
        const currentTime = Date.now();
        const timeDiff = currentTime - lastTokenSwitchTime;
        const minutesPassed = Math.floor(timeDiff / (1000 * 60));

        // Check if the timeout duration has been exceeded
        if (minutesPassed >= 0.5) {
          console.log('Switching to another model token after timeout');
          currentRetries = 0;
          lastTokenSwitchTime = currentTime;

          // Increment the current token index and get the next model token
          currentTokenIndex = (currentTokenIndex + 1) % modelTokens.length;
          modelToken = modelTokens[currentTokenIndex];
        } else {
          console.log('Still within timeout duration, delaying request');
          await new Promise(resolve => setTimeout(resolve, retryDelay));
        }
      }

      // Retry the query with the new model token
      return await executeQuery(data, modelToken, currentTokenIndex);
    } else {
      console.log('Received HTTP error. Slowing down request rate.');
	  
	  // Check if circuit breaker threshold has been reached
      if (currentRetries >= circuitBreakerThreshold) {
        const currentTime = Date.now();
        const timeDiff = currentTime - lastTokenSwitchTime;

        if (timeDiff >= circuitBreakerResetTime) {
          console.log('Resetting circuit breaker');
          currentRetries = 0;
        } else {
          console.log('Circuit breaker active, delaying request');
          await new Promise(resolve => setTimeout(resolve, retryDelay));
        }
      } else {
        await new Promise(resolve => setTimeout(resolve, retryDelay));
      }

      // Calculate the next retry delay with jitter
      const exponentialDelay = Math.pow(2, currentRetries) * minDelay;
      retryDelay = Math.min(exponentialDelay + Math.random() * jitterRange, maxDelay);

      currentRetries++;

      // Retry the query with the same model token
      return await executeQuery(data, modelToken, currentTokenIndex);
    }
  }
}
document.addEventListener('DOMContentLoaded', function() {
  handleResize();
  updateTotalLimit();
});

function autoQueueChanged() {
  if (generateInterval) {
    clearInterval(generateInterval);
  }

  const autoQueueActive = document.getElementById('autoQueueCheckbox').checked;

  if (autoQueueActive) {
    const interval = parseInt(document.getElementById('intervalInput').value) * 1000;
    generateInterval = setInterval(generateImage, interval);
  }
}

async function generateImage() {
  if (isGenerating || autoQueueActive) {
    return;
  }
  
  if (galleryArray.length >= totalLimit) {
    if (autoSaveEnabled) {
      saveAllImages().then(() => {
        clearGallery();
      });
    } else {
      clearGallery();
    }
    return;
  }

function clearGallery() {
  galleryArray.length = 0;
  updateImageCounter();
  bufferContainer.innerHTML = "";
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  if (autoQueueActive) {
    generateInterval = setInterval(generateImage, interval);
  }
}


  
  isGenerating = true;
  
  const inputText = document.getElementById('inputTextArea').value;
  const inputText2 = document.getElementById('inputTextArea2').value;
  const encodedInputText = encodeURIComponent(inputText);
  const encodedInputText2 = encodeURIComponent(inputText2);

  document.addEventListener('click', function(e) {
    const target = e.target;
    if (target != inputTextArea && target != inputTextArea2) {
      inputTextArea.style.height = '';
      inputTextArea2.style.height = '';
    }
  });
  
progressBarFilled.style.background = 'linear-gradient(to left,  transparent 30%, #aabbee 100%, #010130 10px), linear-gradient(to right,  transparent 90%, #aabbee 50%, #010130 16px)';
progressBarFilled.style.backgroundSize = "100%, 10px";
progressBarFilled.style.backgroundPosition = 'center';

   const doneSpanElem=document.createElement("span");
       doneSpanElem.innerText="processing…";
       doneSpanElem.style.fontSize="14px";
doneSpanElem.style.fontWeight="bold";
  doneSpanElem.style.letterSpacing="2px";
    // Apply styles to center text horizontally
       doneSpanElem.style.position= "absolute";
        doneSpanElem.style.left= "50%";
        doneSpanElem.style.top= "50%";
        doneSpanElem.style.transform= "translate(-50%, -50%)";
        

    // Add Done! element as child of progress bar 
      progressBarFilled.appendChild(doneSpanElem);

      //Remove processing text 
      const processingTextNode=document.querySelector('.progress-bar .processing-text')
      if (processingTextNode) {
          progressBarFilled.removeChild(processingTextNode)
     }

  setTimeout(() => {
    const startTime = Date.now();
    const timeLeft = Math.floor(estimatedTime / 1000);

    const interval = setInterval(function() {
      if (isGenerating) {
        const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
        const progress = Math.floor((elapsedTime / timeLeft) * 1000);
        progressBarFilled.style.width = progress + '%';
      }
    }, 1000); ```