<input type="number" id="number">
<button onlcick="countdown()">COUNTDOWN</button>
var t = document.getElementById('number').value;
function countdown() {
setTimeout(function(){alert("hi!");}, t);
}
</script>
I want setTimeout
to get variable t
. Variable t
will get whatever 4 digit number is in the input
tag & when your press the button, it will start subtracting. However, when I try press the button it does not do this.
Is there something wrong with the code? Or, is this not how you do it?
<input type="number" id="number">
<button onlcick="countdown()">COUNTDOWN</button>
var t = document.getElementById('number').value;
function countdown() {
setTimeout(function(){alert("hi!");}, t);
}
</script>
I want setTimeout
to get variable t
. Variable t
will get whatever 4 digit number is in the input
tag & when your press the button, it will start subtracting. However, when I try press the button it does not do this.
Is there something wrong with the code? Or, is this not how you do it?
- 1 " it will start subtracting" What will start subtracting? – j08691 Commented Feb 25, 2015 at 20:32
-
What ever the value for the
input
tag is. – Carlos Carlsen Commented Feb 25, 2015 at 20:34 - Whatever the value is in the INPUT TAG – Carlos Carlsen Commented Feb 25, 2015 at 20:42
4 Answers
Reset to default 4You have 2 mistakes, first change onlcick
to onclick
, and add t
variable to function countdown
because you need get value after click, but in your example variable will be empty
function countdown() {
var t = document.getElementById('number').value;
setTimeout(function(){alert("hi!");}, t);
}
Example
Also you can clear timeout in order to start new timer after click, like so
var timer;
function countdown() {
var t = document.getElementById('number').value;
clearTimeout(timer);
timer = setTimeout(function(){alert("hi!");}, t);
}
Example
Main problem: you need to read input value inside of the function when it's called:
function countdown() {
var t = document.getElementById('number').value;
setTimeout(function(){alert("hi!");}, t);
}
The variable t
is initialized on page load and will not update automatically when input value changes. This is your responsibility to read new value from input.
And another thing (which is probably just a typo) but yes, attribute should be onclick
.
It appears you have a typo in your button it should be <button onclick="countdown()">COUNTDOWN</button>
Define pointer for timeout
window.hTimeOut = null;
function countdown() {
reset previously called and not finished countdown (timeout)
if(window.hTimeOut!=null) clearTimeout(window.hTimeOut);
create new timeout
window.hTimeOut = setTimeout(function(){
alert("hi!");
reset timeout pointer after it finished
window.hTimeOut!=null;
and pass new value of time into it
}, document.getElementById('number').value);
}