简体   繁体   中英

x is not defined, setTimeout problem

With the following code I get a clock is not defined error, why?

$(function(){   
    function clock() {
        var nd = new Date();
        var h, m, s;
        h = nd.getHours();
        m = nd.getMinutes();
        s = nd.getSeconds();
        if (h <= 9) h = "0" + h;
        if (m <= 9) m = "0" + m;
        if (s <= 9) s = "0" + s;
        $('#digital-clock .hour').text(h+':');
        $('#digital-clock .min').text(m+':');
        $('#digital-clock .sec').text(s);
    }
    setTimeout('clock()', 1000);
});

Because when you pass a string to setTimeout , the code inside it will be executed in global scope at timeout time. Code in global scope doesn't have access to any of the local variables present at the time you call setTimeout .

Don't pass a string to setTimeout , it invariably sucks (it's basically a deferred eval , and we all hate eval eh?). Instead use a Function object:

setTimeout(clock, 1000);

you can use an inline function expression to create your function too, for example:

setTimeout(function() {
    var nd= new Date();
    ...
}, 1000);

Try this:

$(function(){   
    function clock() {
        var nd = new Date();
        var h, m, s;
        h = nd.getHours();
        m = nd.getMinutes();
        s = nd.getSeconds();
        if (h <= 9) h = "0" + h;
        if (m <= 9) m = "0" + m;
        if (s <= 9) s = "0" + s;
        $('#digital-clock .hour').text(h+':');
        $('#digital-clock .min').text(m+':');
        $('#digital-clock .sec').text(s);
    }
    setTimeout(clock, 1000);
});

What's wrong with this?

$(function(){
    setTimeout(function() {
        var nd = new Date();
        var h, m, s;
        h = nd.getHours();
        m = nd.getMinutes();
        s = nd.getSeconds();
        if (h <= 9) h = "0" + h;
        if (m <= 9) m = "0" + m;
        if (s <= 9) s = "0" + s;
        $('#digital-clock .hour').text(h+':');
        $('#digital-clock .min').text(m+':');
        $('#digital-clock .sec').text(s);
    }, 1000);
});

Unless there's some reason you need to reference the function by name later... ?

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