0

I am quite new to p5 and would need some advice.

Is it possible to trigger an action only every few seconds? For example: After two seconds i++;

If I use draw() or an own loop function it just goes way to fast.

Thanks a lot. Max

Skaend
  • 27
  • 6
  • Sure, it's possible. Every `draw()` invocation could test `Date.now()` against a cached `lastFired` date, and if it's greater than `x` seconds, save the new `lastFired` and do the thing you want to do every `x` seconds. Could you share your code so far as a [mcve], please? – ggorlen Jan 17 '22 at 19:10
  • Thank you. That's a big brain solution. :D – Skaend Jan 17 '22 at 20:47

1 Answers1

1

you can make use of setInterval(function, delay) as shown below:

let counter = 0;

function increment() {
  counter++;
}

function setup() {
  createCanvas(400, 400);
  setInterval(increment, 2000); // 2000 ms = every 2 seconds
  fill(0);
}

function draw() {
  background(220);
  text(counter, 100, 100);
}

I have set up an Example Sketch for you here.

You can read more about setInterval on MDN

Waldemar Lehner
  • 875
  • 10
  • 8
  • Wow, that's handy. Didn't know sth. like this exists in P5. Why isn't it mentioned in their references? – Skaend Jan 17 '22 at 20:44
  • `setInterval(increment, 2000); // 2000 ms = every 2 seconds` is somewhat misleading. The 2000 parameter to `setInterval` means "re-call at least 2 seconds after the last call". The delays will accrue and begin to drift over time. `Date` gives you a mechanism to correct the drift, and you'll probably want to poll `Date` inside `draw()` which is a tight `requestAnimationFrame` loop. – ggorlen Jan 17 '22 at 20:50
  • @Skaend It's not mentioned because it's not part of P5.js, but rather a feature of JS. – Waldemar Lehner Jan 17 '22 at 20:54
  • @ggorlen But why does it drift over time? I dont get that – Skaend Jan 17 '22 at 21:46
  • That's how it was designed. If the contract is "fire this at least 2 seconds from now", the script might get bogged down doing other heavy tasks and it might not fire for 2.1 seconds. Now all subsequent calls are off, and maybe the next one after that won't fire for 2.3 seconds after the last one. leading to .4 seconds of drift that just keeps getting worse. There is no timer that internally corrects this. See [How to create an accurate timer in javascript?](https://stackoverflow.com/questions/29971898/how-to-create-an-accurate-timer-in-javascript/29972322#29972322) – ggorlen Jan 17 '22 at 22:00