Se7eN
Se7eN

Reputation: 608

Calling draw() in draw() to increase speed

I'm wondering if calling draw() in draw() is right as I've created a 10 PRINT clone in JavaScript using p5.js inspired from this: Daniel Shiffman's Coding Challenge: 10 PRINT

I tried to call draw() from draw() with an 80% probability to increase the speed and it worked. Here's my implementation:

var x = 0, y = 0;
var space = 10;

function setup() {
  createCanvas(window.innerWidth, window.innerHeight);
  background(0);
}

function draw() {
  stroke(255);
  strokeWeight(2);

  if(random() < 0.8) {
    draw();
  }

  if(random() > 0.5) {
    stroke('#F26C4D');
    line(x, y, x + space, y + space);
  }
  else {
    stroke(255);
    line(x, y + space, x + space, y);
  }

  x += space;

  if(x >= width) {
    x = 0;
    y += space;
  }
}

But I don't know if it's safe to do this, so it would be great if someone could suggest a method to increase its speed if this one is not safe?

Upvotes: 0

Views: 294

Answers (1)

Kevin Workman
Kevin Workman

Reputation: 42176

What you're doing is called recursion. This will work for this simple sketch, but you're going to have a couple issues:

  • The framerate is not uniform. You'll notice this if you start doing animations.
  • It's a little hard to follow, and will get more difficult in more advanced sketches.
  • If you adjusted the probability, it's possible you would hit a stack overflow (the error, not this site).

A simpler solution would be to simply set the framerate using the frameRate() function.

This code would cause the draw() function to be called 80 times per second instead of 60:

function setup(){
  createCanvas(500, 500);
  frameRate(80);
}

More info can be found in the reference.

Or if you want to play with your approach, you might think about getting rid of the recursion and extracting your drawing code into a separate function that you then call from draw():

function draw(){
  myDrawFunction();
  if(random() < .8){
    myDrawFunction();
  }
}

You could then do something like loop a random number of times. But honestly your best bet is probably to just set the framerate and let P5.js do it for you.

Upvotes: 2

Related Questions