TransWikia.com

Getting setTimeout() to work with loading a page

Stack Overflow Asked on November 10, 2021

I am trying to move an element in a page after the page loads. I’m trying to get the element to load, and then move after three seconds. Instead, the element just moves immediately on the page load. Here is my code so far:

<!DOCTYPE html>
<html>
<style>
  #container {
    width: 400px;
    height: 400px;
    position: relative;
  }
  
  #animate {
    width: 50px;
    height: 50px;
    position: absolute;
    background-color: red;
  }
</style>

<body id="body">
  <div id="container">
    <div id="animate"></div>
  </div>

  <script>
    var elem = document.getElementById("animate");

    function myMove(element) {
      var posx = 0;
      var posy = 25;
      var opacity = 0;
      var id = setInterval(frame, 40);

      function frame() {
        if (posx == 10) {
          clearInterval(id);
        } else {
          posx++;
          opacity = opacity + .1
          element.style.top = posy + "%";
          element.style.left = posx + "%";
          element.style.opacity = opacity;
        }
      }
    }
    document.getElementById("body").addEventListener("load", setTimeout(myMove(elem), 3000))
  </script>

</body>

</html>

Any help would be greatly appreciated.

3 Answers

Currently, the myMove methods execute immediately. To avoid this you can use arrow functions supported in ES6 or move myMove to a function

using arrow function (supported in ES6):

document.getElementById('body').addEventListener(
  'load',
  setTimeout(() => myMove(elem), 3000),
);

Convert to function

document.getElementById('body').addEventListener(
  'load',
  setTimeout(function () {
    myMove(elem);
  }, 3000),
);

Answered by Muhammad Saqlain on November 10, 2021

So basically you need this:

// Run at DOM loaded
document.addEventListener("DOMContentLoaded", function() {
  console.log('DOM is loaded');
  // Move
  setTimeout(function(){ myMove(elem); }, 3000)
});

OR


// Run at full page load
window.addEventListener("load", function() {
  console.log('Page is loaded');
  // Move
  setTimeout(function(){ myMove(elem); }, 3000)
});

Answered by tarkh on November 10, 2021

You need to do

setTimeout(() => myMove(elem), 3000)

otherwise it sets a timeout for whatever myMove(elem) returns, which means myMove(elem) runs immediately

Answered by dave on November 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP