const url = "http://students.a-level.com.ua:10012"; const nick = document.getElementById("nick"); const message = document.getElementById("message"); const btnSendMessage = document.getElementById("send"); const container = document.getElementById("container"); let nextMessageId = 1; let delay = 5000; getMessages() // function checkLoop(){ // getDataFromServer(); // setTimeout(checkLoop, delay) // } // другой способ setInterval(getMessages, delay) function getMessages(){ jsonPost(url, {func: "getMessages", messageId: nextMessageId}) .then((response)=>response.json()) .then(data=>{ nextMessageId = data.nextMessageId; updateMessages(data.data) }) } function jsonPost(url, data) { return fetch(url, { method: "POST", body: JSON.stringify(data) }) } function updateMessages(messageList){ messageList.forEach(msg => { newGotMessage(msg) }); } function newGotMessage({nick,message,timestamp}){ const newBlock = document.createElement("div"); newBlock.classList.add("block") const time = new Date(timestamp); let html = ""; html += `
${nick}
`; html += `
` html += `${time.toString().substring(16,24)}
` newBlock.innerHTML = html; container.prepend(newBlock) } btnSendMessage.addEventListener("click", sendAndCheck) async function sendAndCheck(){ await sendMessage(); getMessages() message.value = ""; } async function sendMessage(){ jsonPost(url, {func: "addMessage", nick: nick.value, message: message.value}) }