2014-09-29 81 views
-1

我有一个简单的JS对象,模拟交通灯:JavaScript的setTimeout的不工作

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(); 
} 

但是当我做一个TrafficLight对象(如var a = new TrafficLight(1000, 1000, 1000);),每a.state()调用返回​​(使交通灯没有按”牛逼通过定时器改变它的状态。这有什么错我的代码?

+1

* “JavaScript的setTimeout的不起作用” *是这样,你知道的。但它不是JavaScript,它是浏览器的。 – 2014-09-29 09:13:57

回答

3

你不正确地调用setTimeout

变化

setTimeout(delay, func); 

setTimeout(func, delay); 
+2

无类型语言的乐趣.. – 2014-09-29 09:14:39

+1

@OliverWatkins这是真的,但在这种情况下,我要检查的第一件事是不起作用的函数的文档。 – GuyT 2014-09-29 09:17:16