在Settimeout(JavaScript)中使用毫秒的变量
我正在使用文本区域显示时间,输入字段以获取一个数字和一个按钮来执行该功能:
<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>
对于JavaScript部分,我将输入的值存储在一个毫秒的变量中:
// 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;
但是,当我在Settimeout函数中使用此毫秒变量时,它无效:
function refresh() {
var refreshTime = setTimeout(displayTime, milliseconds);
}
function displayTime() {
var timeNow = new Date();
document.getElementById("demo").innerHTML = timeNow.toLocaleTimeString();
}
如果我手动向Settimeout函数添加一个数字,它将起作用,因此我认为我在创建毫秒变量时做错了什么。有人可以帮我出错吗?谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是您出错的地方: -
当用户没有输入任何值时,您就在一开始就获得了输入的值。因此,
settimeout
接收nan
(因为您试图解析一个空字符串)作为其参数。您可以通过每次单击“刷新”按钮时获取文本框的值来轻松修复。
因此,最终结果看起来像这样: -
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 aNaN
(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:-