简体   繁体   中英

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.

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).

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

Because you are clearing interval before it starts executing. Handle tempo undefined in if. SetInterval is an asynchronus call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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