To avoid memory problems, when creating a dynamic function within loops, register it as a global variable, and check if it has already been set