JS请求队列

<!DOCTYPE html>
<html>
<head>
  <title>Request Queue</title>
</head>
<body>
  <button id="requestButton">Send Request</button>
  <script>
    // Function to simulate a request with a delay
    function simulateRequest() {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(`Response for: ${new Date().toLocaleTimeString()}`);
        }, 2000); // Random delay up to 2 seconds
      });
    }

    // Queue class
    class RequestQueue {
      constructor() {
        this.queue = [];
        this.running = false;
      }

      // Function to add a request to the queue
      enqueue(request) {
        this.queue.push(request);
        if (!this.running) {
          this.processQueue();
        }
      }

      // Function to process the queue
      async processQueue() {
        this.running = true;
        while (this.queue.length > 0) {
          const request = this.queue.shift();
          try {
            const response = await simulateRequest(request);
            console.log(response);
          } catch (error) {
            console.error('Error:', error);
          }
        }
        this.running = false;
      }
    }

    // Create a new queue
    const requestQueue = new RequestQueue();

    // Function to handle the button click event
    function handleButtonClick() {
      const request = 'Example Request'; // Replace this with your actual request data
      requestQueue.enqueue(request);
    }

    // Attach click event handler to the button
    const button = document.getElementById('requestButton');
    button.addEventListener('click', handleButtonClick);
  </script>
</body>
</html>

 

© 版权声明
THE END
喜欢就支持一下吧
点赞0赞赏 分享
评论 抢沙发

请登录后发表评论

    请登录后查看评论内容