Home > Software design >  Run loading screen for custom time and remove it
Run loading screen for custom time and remove it

Time:04-14

I need to run the loading screen for 10 seconds and then remove it. And I also tried with setTimeOut but it's not working as I needed. I searched for many tutorials and they only teach how to add a loading animation until the page loads. Please show me the way seniors

const loading = document.querySelector(".loader");
window.addEventListener('load', function() {
  loading.style.display = "none";
});
.loader-wrapper {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  color: white;
  background-color: #242f3f;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 4;
}
<div >Loading...</div>
<div >content</div>

CodePudding user response:

You have to use async functions if you are a planning to wait for the timeout to end and the subsequent code to get executed only after that. You can also hide the content from getting displayed for that much time (for example 10 seconds) and only after timer completes will the content be shown and loader will be hidden.

Note: Any asynchronous code you write is taken out of the normal execution flow and if your further logic (synchronous or asynchronous) should get executed only after completion of that async task then you have to wait using await keyword.

const loading = document.querySelector(".loader");
const content = document.querySelector(".content");
content.style.display = "none";
window.addEventListener('load', async function() {
  await setTimeout(()=>{
    content.style.display = "block";
    loading.style.display = "none";    
  }, 10000)
});
.loader-wrapper {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  color: white;
  background-color: #242f3f;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 4;
}
<div >Loading...</div>
<div >content</div>

CodePudding user response:

I believe setTimeout shall work fine here. If only you want to block further code execution before loading end, you may use async/await, refer to this post.

const loading = document.querySelector(".loader");
const content = document.querySelector(".countdown");
let countdown = 10

document.addEventListener('DOMContentLoaded', function() {
  setTimeout(() => {
    loading.style.display = "none";
  }, 10000)

  setInterval(() =>{
    countdown--
    content.innerHTML = countdown
  },1000)
});
.loader-wrapper {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  color: white;
  background-color: #242f3f;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 4;
}
<div >Loading...</div>
<div >content</div>
<div >10</div>

  • Related