function loopable(n, func) {
return function (...args) {
function looper() {
if (n === 0) {
return undefined;
}
n -= 1;
func(...args);
looper();
}
looper();
};
}
It works as expected in dev console, when I pass it console.log and some number, however it fails for other functions that draw stuff. What’s wrong with it?
usage:
var writeString_loopable = loopable(n, console.log);
writeString_loopable('hello');
This question is not related to p5.js but to javascript. My suggestion to you is to write readable code. Instead of going fancy with ...args, replace that and explicitly define the variables used in your function.
Why are you calling looper within looper? In fact why use recursion in the first place? Couldn’t you just use a simple iterative for loop? The n should be stored as a closure variable so you could simply reference it in the for loop.
You should also probably return a value when calling looper, unless the caller doesn’t care about it.
The error is ‘illegal invocation’ and apparently it’s specific to canvas functions. When I pass ctx.fillRect as an argument to loopable, this is not bound to ctx. The fix was to use the bind function.