I want to change the visibility of the elements of class container_element with an interval of one second one by one.
i tried solve my problem with for loop but when i try to setInterval in for loop it stops and doesnt show anything.
<!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>Task</title>
</head>
<style>
.container {
border: 5px solid;
text-align: center;
}
.container_element {
visibility: hidden;
}
</style>
<body>
<div class="container">
<div class="container_element">🚢</div>
<div class="container_element">🚓</div>
<div class="container_element">✈️</div>
<div class="container_element">🚀</div>
<div class="container_element">🚩</div>
<div class="container_element">🏨</div>
</div>
</body>
</html>
i tried this,but it did not work.
<script>
function showDiv() {
var items = document.querySelectorAll(".container_element");
for (i = 1; i < items.length; i++) {
setInterval(() => {
items[i].style.visibility = 'visible';
}, 1000);
}
}
showDiv();
</script>
2
Answers
Don’t use a loop,
setInterval()
already makes the function repeat. Each iteration of that should make the next element visible.You should use an
async
/await
approach to simplify your logic: