Hello and thank you for reading my post
I have created a basic piece of AJAX. It looks like the following:
<div id="name"></div>
<script>
async function get_name() {
let server = await fetch("pageOneName")
let data = await server.text()
document.querySelector("#name").innerText = data
}
setInterval(get_name, 3000)
</script>
as of now it doesn't really do much but retrieve my first name from the file/url
What I would like to do is...
Display my name multiple times (max 5 times) in multiple rows. One name after 3000, another after 4000, etc.
Like.
What would my approach be here?
You just need to create an interval of 3000, 4000, 5000 to create the name every second after 3 seconds and then create a counter to count the limit, when the limit is reached then clear the intervals.
// initialize the variables.
var counter = 0;
var intervals = [];
// clear all intervals
function clearAllIntervals() {
for (var id of intervals) {
clearInterval(id);
}
}
async function get_name() {
let server = await fetch("pageOneName");
let data = await server.text();
let p = document.createElement("p");
p.append(data);
document.querySelector("#name").append(p);
counter +=1;
// Clear the counter and the intervals show 5 names.
if (counter === 5){
clearAllIntervals();
counter = 0;
}
}
intervals.push(setInterval(get_name, 3000));
intervals.push(setInterval(get_name, 4000));
intervals.push(setInterval(get_name, 5000));
<html>
<body>
<div id="name"></div>
</body>
</html>