index.html 985 B

123456789101112131415161718192021222324252627282930313233
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Long Polling Example</title>
  5. </head>
  6. <body>
  7. <h1>Long Polling Messages</h1>
  8. <div id="messages"></div>
  9. <script>
  10. function poll() {
  11. fetch("/poll")
  12. .then((response) => response.json())
  13. .then((data) => {
  14. const messageDiv = document.getElementById("messages");
  15. messageDiv.innerHTML = "";
  16. data.messages.forEach((message) => {
  17. const newMessage = document.createElement("div");
  18. newMessage.textContent = message;
  19. messageDiv.appendChild(newMessage);
  20. });
  21. setTimeout(poll, 200); // Make the next poll request after 200ms
  22. })
  23. .catch((error) => {
  24. console.error("Polling error:", error);
  25. setTimeout(poll, 5000); // Retry after 5 seconds if there's an error
  26. });
  27. }
  28. // Start the first poll request
  29. poll();
  30. </script>
  31. </body>
  32. </html>