Timed events

This is how to use time functions (you also have day(), month(), year()).
They read your operating system’s clock.
This sketch prints 3 bars proportional to seconds minutes and hours.

function setup() {
  createCanvas(250, 250);

function draw() {

  //update variables with time and date
  s = second();
  m = minute();
  h = hour();

  //change fill
  fill(255, 0, 0);
  //map the lenght of my bar according to my seconds
  var sWidth = map(s, 0, 60, 0, 200);
  //draw a rectangle
  rect(0, 0, sWidth, 50);

  //do the same for minutes and hours
  fill(0, 255, 0);
  var mWidth = map(m, 0, 60, 0, 200);
  rect(0,100, mWidth, 50);

  fill(0, 0, 255);
  var hWidth = map(h, 0, 23, 0, 200);
  rect(0,200, hWidth, 50);


How to make something happen every second

var s;
var lastSecond;

function setup()
  createCanvas(200, 200);

//this function is called 60 times per second
function draw()
  s = second();

  //if the second was updated then do something once
  if (s != lastSecond)
    println("A second elapsed");
    background(random(255), random(255), random(255));
    //update the last second
    lastSecond = s;
    //this variables will be the same until
    //the next second change in the clock

millis: how to make something happen between seconds

Common problem: second() is related to the system clock but millis() count starts as you run the applet. Sometimes you need them to be in sync, for example if you want an analog clock with a second arm moving smoothly:

//the function millis() returns the time elapsed since
//the launch of the sketch in milliseconds

//millisRolloverTime is the time elapsed since
//the last time a second changed in milliseconds
var millisRolloverTime;
var prevSec;

function setup()
  createCanvas(600, 600);
  millisRolloverTime = 0;

function draw()

  //second just changed
  if (prevSec != second () ) {
    //save the current time
    millisRolloverTime = millis();

  //update the value of seconds
  prevSec = second();

  //the current second milliseconds is the current time (in ms)
  //MINUS the last time (in ms) a second changed.
  //I round it because I don't need tiny fractions of milliseconds
  var milliseconds = round(millis() - millisRolloverTime);

  //write it
  text(second() + " " + milliseconds, 10, 20);

  //draw a bar based on it
  var bar = map(milliseconds, 0, 999, 0, width);
  rect(0, 50, bar, 30);
Posted in