A function that takes in a function Y and a number, and returns a function which when called, invokes Y some number of times

please format code with </> button * homework policy * asking questions

function loopable(n, func) {
			return function (...args) {
				function looper() {
					if (n === 0) {
						return undefined;
					n -= 1;

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?


var writeString_loopable = loopable(n, console.log);

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.

What error do you get when you run your code?


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.

In attempting to learn JS, I’m trying alternatives to conventional stuff like loops. How would you improve this particular code?

I haven’t done Cinder on js yet but I would think using arrow functions would be a start.