如何获得设置超时以从输入中读取值

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

本文关键字:输入 读取 何获得 设置 超时      更新时间:2024-05-12
  <input type="number" id="number">
  <button onlcick="countdown()">COUNTDOWN</button>

  var t = document.getElementById('number').value;
function countdown() {
    setTimeout(function(){alert("hi!");}, t);
}
</script>

我想setTimeout获得可变t.可变t将获取input标签中的任何4位数字,当您按下按钮时,它将开始减去。但是,当我尝试按下按钮时,它不会这样做。代码有问题吗?或者,这不是你的做法吗?

你有 2 个错误,首先将onlcick更改为 onclick ,然后将t变量添加到函数countdown,因为您需要在单击后获取值,但在您的示例中变量将为空

function countdown() {
    var t = document.getElementById('number').value;
    setTimeout(function(){alert("hi!");}, t);
}

您还可以清除超时以便在单击后启动新的计时器,如下所示

var timer;
function countdown() {
    var t = document.getElementById('number').value;
    clearTimeout(timer);
    timer = setTimeout(function(){alert("hi!");}, t);
}

主要问题:调用函数时,您需要读取函数内部的输入值:

function countdown() {
    var t = document.getElementById('number').value;
    setTimeout(function(){alert("hi!");}, t);
}

变量t在页面加载时初始化,当输入值更改时不会自动更新。这是您从输入中读取新值的责任。

还有一件事(可能只是一个错字(,但是是的,属性应该是onclick的。

您的按钮中似乎有拼写错误,应该<button onclick="countdown()">COUNTDOWN</button>

定义超时指针

window.hTimeOut = null;
function countdown() {

重置以前调用但未完成的倒计时(超时(

    if(window.hTimeOut!=null) clearTimeout(window.hTimeOut);

创建新的超时

    window.hTimeOut = setTimeout(function(){
            alert("hi!");

完成后重置超时指针

            window.hTimeOut!=null;

并将新的时间价值传递给它

    }, document.getElementById('number').value);
}