How to automate a JavaScript/html traffic light sequence using setinterval?

前端 未结 2 394
北海茫月
北海茫月 2021-01-07 15:30

I am new to JavaScript and i am tying to automate this traffic light sequence. I have used if and if else statements to preform the task but I am unable to automate it so it

2条回答
  •  [愿得一人]
    2021-01-07 16:12

    I would clean things up a bit... you can move all the drawing to one place. Then use a start and stop function. Actually, you can easily combine the start and stop but I will leave that to you. Here you go:

    function light(c) {
      this.current = 0;
      this.colors = ["green", "yellow", "red"];
      this.ctx = c.getContext("2d");
    }
    
    light.prototype.draw = function() {
      this.ctx.beginPath();
      this.ctx.arc(95, 50, 40, 0, 12 * Math.PI);
      this.ctx.fillStyle = this.colors[this.current];
      this.ctx.fill();
    }
    
    light.prototype.start = function() {
      if(this.interval)
        return;
      this.draw();
      this.interval = setInterval(function() {
        this.current = (this.current + 1) % this.colors.length;
        console.log("drawing: ", this.colors[this.current]);
        this.draw();
      }.bind(this), 3000);
    }
    
    light.prototype.stop = function() {
      if (!this.interval)
        return;
      clearInterval(this.interval);
      delete this.interval;
    }
    
    var myLight = new light(document.getElementById("myCanvas"));
    
    
    

提交回复
热议问题