Created
November 18, 2016 17:33
-
-
Save nataliefreed/1d3a74edf9678bfbb7b89ccc7a77cc2f to your computer and use it in GitHub Desktop.
Stoplight timer example using setInterval
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Timer example using setInterval */ | |
var light_state = 0; | |
function setup() { | |
createCanvas(600, 600); | |
noStroke(); | |
//change stoplight state every 1.5 seconds | |
setInterval(change_state, 1500); | |
} | |
function draw() { | |
background(255); | |
//draw back panel of stoplight | |
fill(100); | |
rect(width/2-50, 50, 100, 200, 5); | |
stoplight(light_state); | |
} | |
function change_state() { | |
//Increment light_state by one. Go back to 0 after 2. | |
light_state = (light_state + 1) % 3; | |
} | |
function stoplight(s) { | |
var y; | |
switch(light_state) { | |
case 0: | |
fill(0, 255, 0); | |
y = 100; | |
break; | |
case 1: | |
fill(255, 255, 0); | |
y = 150; | |
break; | |
case 2: | |
fill(255, 0, 0); | |
y = 200; | |
break; | |
default: | |
break; | |
} | |
ellipse(width/2, y, 50, 50); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment