Matt B.
Matt B.

Reputation: 331

Getting setTimeout() to work with loading a page

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.

Upvotes: 0

Views: 1780

Answers (3)

Muhammad Saqlain
Muhammad Saqlain

Reputation: 2202

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),
);

Upvotes: 0

tarkh
tarkh

Reputation: 2549

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)
});

Upvotes: 1

dave
dave

Reputation: 64657

You need to do

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

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

Upvotes: 2

Related Questions