script.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const url = "http://students.a-level.com.ua:10012";
  2. const nick = document.getElementById("nick");
  3. const message = document.getElementById("message");
  4. const btnSendMessage = document.getElementById("send");
  5. const container = document.getElementById("container");
  6. let nextMessageId = 1;
  7. let delay = 5000;
  8. getMessages()
  9. // function checkLoop(){
  10. // getDataFromServer();
  11. // setTimeout(checkLoop, delay)
  12. // }
  13. // другой способ
  14. setInterval(getMessages, delay)
  15. function getMessages(){
  16. jsonPost(url, {func: "getMessages", messageId: nextMessageId})
  17. .then((response)=>response.json())
  18. .then(data=>{
  19. nextMessageId = data.nextMessageId;
  20. updateMessages(data.data)
  21. })
  22. }
  23. function jsonPost(url, data) {
  24. return fetch(url, {
  25. method: "POST",
  26. body: JSON.stringify(data)
  27. })
  28. }
  29. function updateMessages(messageList){
  30. messageList.forEach(msg => {
  31. newGotMessage(msg)
  32. });
  33. }
  34. function newGotMessage({nick,message,timestamp}){
  35. const newBlock = document.createElement("div");
  36. newBlock.classList.add("block")
  37. const time = new Date(timestamp);
  38. let html = "";
  39. html += `<p>${nick}<p>`;
  40. html += `<p class="message">"${message}"</p>`
  41. html += `<p>${time.toString().substring(16,24)}</p>`
  42. newBlock.innerHTML = html;
  43. container.prepend(newBlock)
  44. }
  45. btnSendMessage.addEventListener("click", sendAndCheck)
  46. async function sendAndCheck(){
  47. await sendMessage();
  48. getMessages()
  49. message.value = "";
  50. }
  51. async function sendMessage(){
  52. jsonPost(url, {func: "addMessage", nick: nick.value, message: message.value})
  53. }