使用函数setinterval javascript错误使用函数

using function in setinterval javascript error using function

本文关键字:函数 错误 setinterval javascript      更新时间:2023-09-26

我写了一个简单的定时器为什么这段代码不正确is说Uncaught ReferenceError: a没有定义为什么?

function timeee(sec) {
    document.getElementById("main").innerHTML = sec;
    --sec;
    if (sec == -1) {
        clearInterval(cleartext);
    }
}
function timer() {
    var a = document.getElementById("time").value;
    var cl = setInterval("timeee(a)", 1000);
    window.cleartext = cl;
}

正如您在另一个问题中看到的,当您将setInterval与字符串一起使用时,该函数是在全局作用域中运行的。但是,您的a变量仅在本地设置,因此timeee()函数无法看到它。

尝试使用:

function timer() {
    var a = document.getElementById("time").value;
    var cl = setInterval(function() { timeee(a) }, 1000);
    window.cleartext = cl;
}

或者如果您真的想使用字符串,则将a定义为全局变量:

var a;
function timer() {
    a = document.getElementById("time").value;
    var cl = setInterval("timeee(a)", 1000);
    window.cleartext = cl;
}

为什么?

范围。

考虑:

function timer() {
    var a = document.getElementById("time").value;
    var cl = setInterval("timeee(a)", 1000);
    window.cleartext = cl;
}

a是局部作用域,但是timeee(a)将从全局作用域调用。它不能访问。试一试:

    var cl = setInterval(function(){timeee(a)}, 1000);

所以在闭包中保留的值a注意,这样每次都会传递相同的a值,所以你也需要解决这个问题(Banana的答案是一个选项)。

经过一番思考,我最好的猜测是对"a"的引用不是一个合适的闭包。

这样想:你正在传递一个字符串给setInterval。隐式地,当您将字符串传递给setIntervalsetTimeout时,某处的eval()正在被调用。因为在运行时,解释器不知道变量a在其他地方被使用,所以它会丢弃它。然后,当执行eval时,参数a不再存在。

现在看看你的问题的解决方案:

function timer() {
    var a = document.getElementById("time").value;
    var cl = setInterval(function() { timeee(a) }, 1000);
    window.cleartext = cl;
}

因为解释器知道a以后还会被使用,所以它不会被销毁。