WadeB
WadeB

Reputation: 89

Why won't setTimeout() work?

I am trying to simply make my function wait 3 seconds before running. It seems really straightforward but for some reason, I keep getting a:

slideFunction is not defined

error in the console. It works if I just call the function without trying to use setTimeout. What is wrong here?

window.onclick = slideFunction;

setTimeout(slideFunction, 3000); { 
  document.getElementById('#img3').style.marginLeft = "100px";
}

Upvotes: 0

Views: 50

Answers (3)

WadeB
WadeB

Reputation: 89

Thanks for the help everyone. I did manage to get it to work how I needed using

  function slideFunction(){
  document.getElementById('#img3').style.marginLeft = "100px";
  }

  document.body.onclick = () => setTimeout(slideFunction, 3000);
  }

Upvotes: 0

tao
tao

Reputation: 90013

It works, but the function you are calling needs to be defined and to be a function. Example:

function slideFunction(){
  document.getElementById('img3').style.marginLeft = "100px";
}

document.body.onclick = () => setTimeout(slideFunction, 3000);
#img3 {
  width: 50%;
  border: 1px solid red;
  height: 100px;
  transition: margin-left .3s cubic-bezier(.4,0,.2,1);
}
body,html {height: 100%;margin: 0;}
<div id="img3"></div>
<button onclick="document.location.reload(true)">Reload</button>

A few problems:

  • .getElementById('#img3') is not correct. It's either .getElementById('img3') or .querySelector('#img3'), unless your element's id is really #img3 i.e.: <img id="#img123" src>, in which case it is invalid:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

  • window.onclick should be document.body.onclick

Upvotes: 1

k1dev
k1dev

Reputation: 641

The entire solution you are looking for:

function slideFunction(){
  document.getElementById('#img3').style.marginLeft = "100px";
}
window.onclick = slideFunction;

setTimeout(slideFunction, 3000);

Upvotes: 0

Related Questions