How to wait in p5.js?

by giovanny.lueilwitz , in category: Javascript , 7 months ago

How to wait in p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by aubrey , 6 months ago

@giovanny.lueilwitz 

In p5.js, you can use the setTimeout() function to wait for a specified amount of time before executing a function. Here's an example of how you can use setTimeout() to create a delay in p5.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  
  // Draw a circle
  ellipse(200, 200, 50, 50);
  
  // Wait for 2 seconds before changing the background color
  setTimeout(changeBackgroundColor, 2000);
}

function changeBackgroundColor() {
  background(random(255), random(255), random(255));
}


In this example, the changeBackgroundColor() function will be called after a delay of 2 seconds (2000 milliseconds) using setTimeout(). This will change the background color to a random color every 2 seconds.


It's important to note that using setTimeout() in the draw loop can cause performance issues, as the function will be repeatedly called every frame. It's recommended to use setTimeout() outside of the draw loop if you want to create a one-time delay.

Related Threads:

How to wait for a global/event outside of ember.js?
How to play sounds in p5.js?
How to make a video/gif transparent on p5.js?
How to style a rect.js in p5.js?
How to animate in p5.js?
How to import model in p5.js?