| Reference | Downloads | Github

Custom function not defined when called from a different routine

When running the experiment from the builder in Pavlovia I get the following problem.

I define the following custom function using a code snippet at the beginning of the experiment. It just chooses a random number that I use later. doJitterLine is also defined at the beginning of the experiment.

function jitterLine(doJitterLine) {
    if (doJitterLine) {
        return [3,4,5,6,7][Math.floor(Math.random() * 5)] * (Math.round(Math.random()) * 2 - 1);
    } else {
        return 0;

However, when I try to run it in a code snippet at the end of another routine I get:

***ReferenceError: jitterLine is not defined**.

For now, I just copied the content of the function and pasted it in every routine I need to use it but which is not very optimal.

Is it possible to define a JS function at the beginning of the experiment to reuse it in later routines? If so, what I’m missing in my function definition?


@niclai, you just need to assign your function to a variable name, so PsychoPy can declare the variable / function in global scope:

jitterLine = function(doJitterLine) { ... }

@dvbridges, yeah that sounds very important :sweat_smile:
That function definition was created by the python to JS translator of the builder. Is that a normal thing that function definitions are translated but not assigned to a variable?

Yes, its just the way the translation happens, but you could also just assign your function to a variable in Python and use the new name. This should translate correctly without the need to adapt the JS, e.g., in Python

def myFunction(vars):
    return True
newFunName = myFunction
1 Like