I just started to try asynchronous JS with setTimeout() function. I hardcoded two objects in an JS Array and added one with a method that runs in 3S delay. I've written another method that prints the array (both HTML Response and Console.log). Printing to response does seem to work fine, that is till posts.push(post) called, only two objects get written to HTML Response.
But sometimes console.log() prints 3 objects, either before "begin addpost" or sometimes even before addPost() invocation while addPost is called only after 5000ms. Not sure what am I doing wrong here. Can someone help?
const posts = [{
body: "I am Post One",
title: "Post One"
},
{
body: "I am post two",
title: "Post Two"
}
]
function addPost(post) {
setTimeout(function() {
console.log("begin addpost");
let output = "<p> ";
posts.forEach(function(post) {
output += (post.body + "<br/>");
});
output += "</p>";
document.body.innerHTML = output;
posts.push(post);
console.log("end addpost");
}, 5000);
}
function getPosts() {
setTimeout(function() {
console.log("begin getpost");
console.log(posts);
console.log("end getpost");
}, 1000);
}
console.log(posts);
addPost({
body: "I am post Three",
title: "Post Three"
});
getPosts();