Search code examples
javascriptp5.js

Timed counter in P5.js


I'm trying to set up a counter in P5.js. The counter should sequentially print a number 1 through 10, and there should be 3-second pause in between each print (this process would take a total of 30 seconds).

I am trying to calculate timeElapsed, and for some reason it is returning NaN.

var startTime;

function setup() {
  createCanvas(windowWidth, windowHeight); //set canvas to window width and window height
  background("#dc3787"); //background of pink
  var startTime = millis();
  console.log(startTime);
}

//print i every 3 seconds from 0 - 10

function draw() {
  var timeElapsed = (startTime - millis()); //NaN ?
  console.log(timeElapsed);

  for (let i = 0; i <= 10; i++) {
    if (timeElapsed % 3000 === 0) {
      console.log(i);
    }
  }
}

function windowResized() { //P5 window resize function
  resizeCanvas(windowWidth, windowHeight);
}

Solution

  • You created startTime a second time by using var in setup(), so it only exists in the setup() scope.

    draw() is called 30, 60 or 120 times a second, if you don't use frameRate(), so to still use it to update every frame just save the time the last number was printet (lastPrint) and the number currently displayed (i) and calculate the difference each frame.

    When the difference is 3000 or more the last frame in whoch the number was printed is at least 3 seconds ago so you can print the next.

    var lastPrint;
    var i = 0;
    
    function setup() {
      createCanvas(windowWidth, windowHeight); //set canvas to window width and window height
      background("#dc3787"); //background of pink
      lastPrint = millis() - 3000;
    }
    
    //print i every 3 seconds from 0 - 10
    
    function draw() {
      var timeElapsed = millis() - lastPrint;
      //console.log(timeElapsed);
    
      if (timeElapsed > 3000) {
        i++;
        console.log(i);
        lastPrint = millis();
      }
    }
    
    function windowResized() { //P5 window resize function
      resizeCanvas(windowWidth, windowHeight);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>