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.