Home > Net >  To set a duration time for the page loader animation
To set a duration time for the page loader animation

Time:04-18

I would like to set a minimum time for the loading animation of my website.

I have the following code on HTML:

   <div id="preloader"></div>

   <script>
      var loader = document.getElementById("preloader");

      window.addEventListener("load", function(){
        loader.style.display = "none";
      })

   </script>
</body>

What do I have to add in order to set the loading animation for a mininum of 3 seconds?

Thank in advance.

CodePudding user response:

If you don't care about the actual time taken for the page to load, and only want the animation to last a minimum of 3 seconds, you could wrap your function inside setTimeout with the second parameter equal to 3000 milliseconds, as in this example:

var loader = document.getElementById("preloader");
    
var dismissLoadingScreen = function() {
    loader.style.display = "none";
};
    
var wait3seconds = function() {
    // REFERENCE:  https://www.w3schools.com/jsref/met_win_settimeout.asp
    var result = setTimeout(dismissLoadingScreen, 3000);
};

window.addEventListener("load", wait3seconds);
body {
    background-color: darkblue;
}
#preloader {
    background-color: green;
    color: white;
    height: 100vh;
    width: 100%;
    position: fixed;
    z-index: 100;
}
<body>
    <div id="preloader">this is a div</div>
</body>

Here is the documentation on setTimeout from w3schools: https://www.w3schools.com/jsref/met_win_settimeout.asp

  • Related