Home > Software design >  adding setTimeout to close a preloader
adding setTimeout to close a preloader

Time:06-18

I'm not so good at javascript and I'm trying to add setTimeout to close my preloader after a certain time, but it doesn't work. Can someone help me? Thank you so much.

document.onreadystatechange = function () {
    var e = document.readyState;
    "interactive" == e
        ? ((document.body.style.overflow = "hidden"), (document.getElementById("contents").style.visibility = "hidden"))
        : "complete" == e &&
          setTimeout(function () {
              document.getElementById("interactive"), (document.body.style.overflow = "auto"), (document.getElementById("load").style.visibility = "hidden"), (document.getElementById("contents").style.visibility = "visible");
              
          },
           1e3);
           setTimeout(e, 3500);
};

CodePudding user response:

If I understood correctly what you are trying to achieve , this is what you are looking for.

window.addEventListener('load', () => { // wait to load the page
  setTimeout(() => {
    document.querySelector('.loader').style.display = 'none' // hide the loader after 3.5 seconds
    console.log('loaded')
  }, 3500)
})
<div >Loading...</div>

CodePudding user response:

Don't put the code inside the readystatechange event handler.

document.body.style.overflow = "hidden";
document.getElementById("contents").style.visibility = "hidden";
setTimeout(function() {
    document.body.style.overflow = "auto";
    document.getElementById("load").style.visibility = "hidden";
    document.getElementById("contents").style.visibility = "visible";
}, 3500);
  • Related