xxxxxxxxxx
65
//This shows the basics of Javascript setInterval and setTimer functions
//It sets up the following:
// - A recurring interval of 1 second that changes the background color
// - a one-time function that activates drawing a circle after 5.5 second
// - a "manual" timer that watches millis() and determines when to draw a rectangle.
// - a one time function at 12 seconds that cancels the interval
let bgColor = 0;
let intervalID;
let drawCircle = false;
let drawRectangle = true;
function setup() {
createCanvas(400, 400);
//setInterval will execute the function (referenced or inline) repeatedly at the specified intermal in ms
//Every second update the background color
intervalID = setInterval(
updateBackground, //function reference
1000); //interval
//setTimeout takes the same arguments as setInterval but only executes once
//In 5.5 seconds, drawCircle will be true
setTimeout(
function() { //inline function
print("***Yo from Timeout: " + millis());
drawCircle = true;
},
5500);
//both return a numerical ID reference to the timer.
//You can store the ID to stop the timer in the future
//After 12 seconds stop the background update
setTimeout(
function() {
print("Stopping intervalID " + intervalID);
clearInterval(intervalID);
noLoop(); //why draw if nothing is changing
}, 12000);
}
function draw() {
background(bgColor);
//Here is a basic "manual" time check. See how much time has elapsed.
// if it's after some predetermined time, change state.
if (millis() <8000) drawRectangle = true
else drawRectangle = false;;
if (drawRectangle) {
fill(32, 32, 128);
rectMode(CENTER);
rect(width/2, height/2, width/2, 50);
}
if (drawCircle) {
fill("#29F95E"); //botta green!
ellipse(width/2, height/2, 150, 150);
}
}
//called by setInterval in setup
function updateBackground() {
print("Hi from Interval: " + millis());
bgColor += 16;
}