async function jsonPost(url, data) { return new Promise((resolve, reject) => { var x = new XMLHttpRequest(); x.onerror = () => reject(new Error('jsonPost failed')); //x.setRequestHeader('Content-Type', 'application/json'); x.open("POST", url, true); x.send(JSON.stringify(data)); x.onreadystatechange = () => { if (x.readyState == XMLHttpRequest.DONE && x.status == 200){ resolve(JSON.parse(x.responseText)); } else if (x.status != 200){ reject(new Error('status is not 200')); } } }) } async function sendMessage(nick, message) { jsonPost("http://students.a-level.com.ua:10012", { func: 'addMessage', nick: nick, message: message, author: 'chat' }); } const dateToDataTimeLocal = date => (date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, -1); let timestamp = new Date(); let nextMessageId = 0; async function getMessages() { await jsonPost("http://students.a-level.com.ua:10012", { func: 'getMessages', messageId: nextMessageId }).then(res => { res.data.forEach(el => { let div = document.createElement('div'); div.innerHTML = `${el.nick} : ${el.message}:
${timestamp.toGMTString()}`; chat.prepend(div); nextMessageId++; console.log(nextMessageId); }); }); } send.onclick = async function sendAndCheck() { sendMessage(nick.value, message.value); getMessages(); }; async function checkLoop() { await getMessages().then(() => delay(setTimeout (3000)).then(checkLoop)); } checkLoop();