I am using a text area to display the time, an input field to get a number and a button to execute the function:
<textarea name="demo" id="demo"></textarea><br>
<input type="number" id="seconds" name="seconds"></p><br>
<button type="button" name="refresh" onclick="refresh()">Refresh after number of seconds.</button>
For the javascript portion, I am taking the value of the input and storing it in a millisecond variable:
// store input as a variable:
var seconds = document.getElementById("seconds").value;
// convert input to a number
var milliseconds = parseInt(seconds, 10);
// convert number to milliseconds
milliseconds *= 1000;
But when I use this millisecond variable in the setTimeout function, it doesn't work:
function refresh() {
var refreshTime = setTimeout(displayTime, milliseconds);
}
function displayTime() {
var timeNow = new Date();
document.getElementById("demo").innerHTML = timeNow.toLocaleTimeString();
}
If I manually add a number to the setTimeout function, it will work, so I'm thinking I did something wrong in creating the millisecond variable. Could someone help me where I went wrong? Thanks!
This is where you went wrong:-
You are getting the value of the input at the very beginning, when the user has not inputted any value. Thus setTimeout
receives a NaN
(because you are trying to parse an empty string) as its argument.
You can fix that very easily, by getting the value of the text box every time the refresh button is clicked.
So the final result would look like this:-
function refresh() {
// store input as a variable:
var seconds = document.getElementById("seconds").value;
// convert input to a number
var milliseconds = parseInt(seconds); // You dont need to pass in a second argument because by default radix is 10.
// convert number to milliseconds
milliseconds *= 1000;
var refreshTime = setTimeout(displayTime, milliseconds);
}
function displayTime() {
var timeNow = new Date();
document.getElementById("demo").innerHTML = timeNow.toLocaleTimeString();
}
<textarea name="demo" id="demo"></textarea><br>
<!-- I have added a min attribute to restrict it from being negative -->
<input type="number" min="0" id="seconds" name="seconds"></p><br>
<button type="button" name="refresh" onclick="refresh()">Refresh after number of seconds.</button>