Carlos Carlsen
Carlos Carlsen

Reputation: 373

How do I get setTimeout to read the value from the INPUT?

  <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?

Upvotes: 2

Views: 2373

Answers (4)

Anton Y. Reuchenko
Anton Y. Reuchenko

Reputation: 443

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

Upvotes: 1

dmamills
dmamills

Reputation: 197

It appears you have a typo in your button it should be <button onclick="countdown()">COUNTDOWN</button>

Upvotes: 1

Oleksandr T.
Oleksandr T.

Reputation: 77482

You 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

Upvotes: 4

dfsq
dfsq

Reputation: 193261

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.

Upvotes: 1

Related Questions