1

If I directly insert the method document.getElementById in the method setTimeout it works fine

1.

<!DOCTYPE html>
<html>
<body>

<p>Click the button to wait 3 seconds, then alert "Hello".</p>

<button onclick="myFunction()">Try it</button>

<script>


function myFunction() {
    setTimeout(function(){ alert("Hello"); }, document.getElementById("numbers").value);
}
</script>
<input id="numbers" type="textbox"  />
</body>
</html>

2.

<!DOCTYPE html>
<html>
<body>

<p>Click the button to wait 3 seconds, then alert "Hello".</p>

<button onclick="myFunction()">Try it</button>

<script>

var numbers = document.getElementById("numbers").value
function myFunction() {
    setTimeout(function(){ alert("Hello"); }, numbers);
}
</script>
<input id="numbers" type="textbox"  />
</body>
</html>

Why the second one doesn't work? I think that the var numbers returns null, but I don't know why.

Willem Van Onsem
  • 321,217
  • 26
  • 295
  • 405
Dante90
  • 11
  • 1
  • 4

3 Answers3

0

In the first version you are retrieving the element and its value when the click event fires and calls the attached handler. In that moment the input field has a value which is returned.

In the 2nd version you are retrieving the input element and its value when the input field does not exists in the DOM, thus null is used when the handler is called. Obviously you should go for the former.

wiredolphin
  • 971
  • 13
  • 23
  • Script tags do not validate outside of the `` or `` tags. The best place to put this script would probably be right before the closing `` tag. – Matt Dalzell Dec 07 '15 at 20:04
0

The line var numbers = document.getElementById("numbers").value is being executed on the load of your page, numbers does not exist yet.

gmiley
  • 6,181
  • 1
  • 8
  • 22
0

Like @gmiley has said, numbers doesn't exist it yet. You should include:

var numbers = document.getElementById("numbers").value

inside of your function.

Also, on a side note...It's probably not best to put your javascript in the middle of the file. I almost didn't see the 'input' after the 'script' tags.

Anonymous
  • 1,878
  • 2
  • 27
  • 33