Fabio97 Fabio97 - 4 months ago 23
jQuery Question

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:

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.

Answer

Because there is no variable tempo that exist in global scope (or any scope that the stop click handler can reach).

When you declare a variable with var inside a function that variable gets deleted when the function returns:

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:

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