2014-09-29 37 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