We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello all,
I recently started learning p5js about a month ago, by following Daniel Shiffman's video tutorials on youtube. These videos are great and he makes the learning process much more painless. I can not appreciate enough. Thank you and thank you again.
Today I was studying closures and coding along 9.6: JavaScript Closure - p5.js Tutorial. I always try to go and code something a bit extra than the tutorials do.
Program creates two paragraph elements and names them as timer1 and timer2 at setup, then changes them to counters at different rates. Without setTimeout(), timer1 counts with seconds and timer2 goes with half seconds. So timer2 starts half a second earlier than timer1. Here is the code:
var timer1;
var timer2;
function setup() {
noCanvas();
timer1 = createP('timer1');
timer2 = createP('timer2');
makeTimer(timer1, 1000);
setTimeout(makeTimer(timer2, 500), 1000);
//could not figure out why setTimeout is not working
}
function makeTimer(elt, time) {
var counter = 0;
setInterval(timeThat, time);
function timeThat() {
elt.html(counter);
counter++;
}
}
I tried to synchronize just the start time of both timers. Interestingly, the program is working but setTimeout for timer2 doesn't seem to work, it still starts half a second earlier than timer1. Could not figure out why it is not working.
Answers
This statement doesn't make any sense:
setTimeout(makeTimer(timer2, 500), 1000);
B/c invoking makeTimer() doesn't return anything. Therefore undefined is passed to setTimeout().
setTimeout(() => makeTimer(timer2, 500), 500);
Shorter version for makeTimer(): :ar!
There's another alternative syntax for
setTimeout(() => makeTimer(timer2, 500), 500);
: L-)setTimeout(makeTimer, 500, timer2, 500);
Check all available overloaded signatures for setTimeout() at the link below: :-B
https://Developer.Mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout
BtW, I've refactored your sketch and posted it online at the link below. Check it out: :bz
https://OpenProcessing.org/sketch/458021
index.html:
sketch.js: