Why is a function being passed in?

Viewed 41
loader.load('scene.gltf', function(gltf){
  car = gltf.scene.children[0];
  car.scale.set(0.5,0.5,0.5);
  scene.add(gltf.scene);
  animate();
});

I found this bit of code while browsing documentation. Why and how are we passing in a complete function as a argument. Im new to JS so please guide me to the right way. :)

1 Answers

According to the three.js documentation:

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : null

url — the path or URL to the file. This can also be a Data URI.
onLoad — Will be called when load completes. The argument will be the loaded object.
onProgress — Will be called while load progresses. The argument will be the XMLHttpRequest instance, which contains .total and .loaded bytes.
onError — Will be called when load errors.  

Begin loading from url and call onLoad with the parsed response content. 

Thus the second argument must be of type Function, commonly called "callback", which in this particular case will be executed when the resource is finished loading.

Callback functions are a common pattern in many programming languages, JavaScript included. They serve as a way to execute code at a given time / when something is happening / has happened.

Related