Browse Source

HW<13> done

Andrey 1 year ago
parent
commit
8770648f0e
1 changed files with 103 additions and 0 deletions
  1. 103 0
      Dz13 js/Dz13 js.html

+ 103 - 0
Dz13 js/Dz13 js.html

@@ -0,0 +1,103 @@
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+    <meta charset="UTF-8">
+    <meta http-equiv="X-UA-Compatible" content="IE=edge">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Document</title>
+    <style>
+        body {
+            display: flex;
+            flex-direction: column;
+            align-items: center;
+        }
+
+        .msg-container {
+            display: flex;
+            flex-direction: column;
+            width: 400px;
+        }
+    </style>
+</head>
+
+<body>
+    <form>
+        <input type="text" id="login" placeholder="Name" />
+        <input type="text" id="message" placeholder="Message" />
+        <button id="btn">Send</button>
+    </form>
+    <div class="msg-container"></div>
+    <script>
+        const url = "http://students.a-level.com.ua:10012";
+
+        const msgContainer = document.querySelector('.msg-container');
+        const login = document.querySelector('#login');
+        const message = document.querySelector('#message');
+        const btn = document.querySelector('#btn');
+
+        let messageId = 0;
+
+        async function jsonPost(url, data) {
+            try {
+                const response = await fetch(url, {
+                    method: "POST",
+                    body: JSON.stringify(data),
+                });
+                const result = response.json();
+                return response.ok ? result : new Error("status is not 200");
+            } catch (error) {
+                return new Error("jsonPost failed");
+            }
+        }
+        async function sendMessage() {
+            jsonPost(url, {
+                func: "addMessage",
+                nick: login.value,
+                message: message.value,
+            });
+        }
+
+        async function getMessages() {
+            let a = await jsonPost(url, {
+                func: "getMessages",
+                nick: login.value,
+                message: message.value,
+                messageId: messageId,
+            });
+            let msgArray = a.data;
+            msgArray.forEach(msg => {
+                const text = document.createElement("p")
+                messageId = a.nextMessageId;
+                text.innerHTML = `(ID:${messageId})  ${msg.nick}: ${msg.message}`
+                msgContainer.prepend(text)
+
+            });
+        }
+
+        btn.onclick = async function sendAndCheck(e) {
+            e.preventDefault();
+            await sendMessage()
+            await getMessages()
+        }
+       
+        const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms));
+
+        (async function checkLoop() {
+            while (true) {
+                await delay(3000);
+                getMessages();
+            }
+        })();
+
+        //async function sendMessage(nick, message) отсылает сообщение.
+        //async function getMessages() получает сообщения и отрисовывает их в DOM
+        //async function sendAndCheck() использует две предыдущие для минимизации задержки между отправкой сообщения и приходом их.Именно эта функция должна запускаться по кнопке.
+        //async function checkLoop() использует delay и бесконечный цикл для периодического запуска getMessages().
+
+       
+    </script>
+
+</body>
+
+</html>