简体   繁体   English

为什么出现此“ Uncaught ReferenceError:未定义速度”错误?

[英]Why this “Uncaught ReferenceError: tempo is not defined” error?

I've got the following code: 我有以下代码:

$("#avvia_cronometro").click(function() {
    var tempo = setInterval(function() {
        cronometro();
        $("#tempo_cronometro").html((h)+":"+(min)+":"+(sec));
    }, 1000);
});
$("#stop_cronometro").click(function() {
    clearInterval(tempo);
});

function cronometro() {
    if (sec == 59) {
        min +=1;
        if (min == 59) {
            h+=1;
            min=0;
        }
        sec=0;
    }
    sec+=1;
}

When I click on #stop_cronometro it doesn't work and it says: 当我单击#stop_cronometro它不起作用,并显示:

Uncaught ReferenceError: tempo is not defined

How can I fix? 我该如何解决?

If I click on #avvia_cronometro it starts with the time so it's work. 如果单击#avvia_cronometro它会从时间开始,因此可以正常工作。

Well, it happens because the variable scope inside separate functions, when a variable is declared inside a function, it will be only acessible to itself and the child functions. 好吧,发生这种情况的原因是,在单独的函数内部的变量作用域,当在函数内部声明变量时,仅对自身和子函数是必需的。

In you case I suggest you make "tempo" variable global: 在这种情况下,我建议您将“速度”变量设置为全局变量:

var tempo = null;
$("#avvia_cronometro").click(function() {
    tempo = setInterval(function() {
        cronometro();
        $("#tempo_cronometro").html((h)+":"+(min)+":"+(sec));
    }, 1000);
});
$("#stop_cronometro").click(function() {
    clearInterval(tempo);
});

function cronometro() {
    if (sec == 59) {
        min +=1;
        if (min == 59) {
            h+=1;
            min=0;
        }
        sec=0;
    }
    sec+=1;
}

Because there is no variable tempo that exist in global scope (or any scope that the stop click handler can reach). 因为在全局范围(或​​停止点击处理程序可以到达的任何范围)中不存在可变tempo

When you declare a variable with var inside a function that variable gets deleted when the function returns: 当在函数内部使用var声明变量时,该函数返回时该变量将被删除:

function foo () {
    var bar = 1;
}
foo();
console.log(bar); // uncaught reference error - "bar" doesn't exist

If you need a global variable, use it without the var : 如果需要全局变量,请在不使用var情况下使用它:

function foo () {
    bar = 1;
}
foo();
console.log(bar); // prints 1

However, I would generally not recommend this since it looks like an error to future maintainers. 但是,我通常不建议这样做,因为这对于将来的维护者来说似乎是一个错误。 Instead, declare the global variable explicitly in global scope to clearly show your intention: 而是在全局范围内显式声明全局变量,以清楚地表明您的意图:

var bar = null;
function foo() {
    bar = 1;
}
foo();
console.log(bar); // prints 1

Because you are clearing interval before it starts executing. 因为您正在清除间隔后才开始执行。 Handle tempo undefined in if. 处理if中未定义的速度。 SetInterval is an asynchronus call. SetInterval是一个异步调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM