简体   繁体   中英

JavaScript's setTimeout doesn't work

I have a simple JS object which emulates traffic lights:

function TrafficLight(redTime, yellowTime, greenTime) {
    var self = this;

    this.__timer = null;
    this.__state = null;
    this.__redTime = redTime;
    this.__yellowTime = yellowTime;
    this.__greenTime = greenTime;

    var setnewtimer = function (delay, func) {
        console.log('SET!');
        if (self.__timer) {
            clearTimeout(this.__timer);
        }
        self.__timer = setTimeout(delay, func);
    };

    TrafficLight.prototype.toRed = function () {
        this.__state = 'red';
        setnewtimer(this.__redTime, function () {
            console.log('RED!');
            self.toGreen();
        });
    };

    TrafficLight.prototype.toGreen = function () {
        this.__state = 'green';
        setnewtimer(this.__greenTime, function () {
            console.log('GREEN');
            self.toYellow();
        });
    };

    TrafficLight.prototype.toYellow = function () {
        this.__state = 'yellow';
        setnewtimer(this.__yellowTime, function () {
            console.log('YELLOW');
            self.toRed();
        });
    };

    TrafficLight.prototype.state = function () {
        return this.__state;
    };

    this.toGreen();
}

But when I make a TrafficLight object (like var a = new TrafficLight(1000, 1000, 1000); ), every a.state() call returns green (so traffic light doesn't change its state by timer. What's wrong with my code?

You don't call setTimeout correctly.

Change

setTimeout(delay, func);

to

setTimeout(func, delay);

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