Currently, I am following along with a tutorial at this link and I've come across some syntax that is confusing to me.
The goal is to have "hello" logged to the console every time I scroll.
function moveCamera() {
console.log("hello");
}
document.body.onscroll = moveCamera()
function moveCamera() {
console.log("hello");
}
document.body.onscroll = moveCamera
In the first scenario, "hello" is logged once but does not repeat with further scrolling.
On the other hand, in the second scenario, "hello" is logged every time there is a scroll event.
I realize that in the second scenario, moveCamera is passing a copy of the function, essentially creating a function that looks like this:
document.body.onscroll = function () {
console.log("Hello");
}
Yet, I'm still puzzled as to why calling moveCamera() with parentheses does not function as expected and produces unwanted results.
UPDATE: I've come up with a simple way to distinguish when to use parentheses and when not to. I'm sharing it here even though my question was marked as a duplicate.
Examples Without Parentheses
// Example 1: Use reference when assigning
document.body.onscroll = moveCamera;
// Example 2: Use reference when event listening
document.body.addEventListener("scroll", moveCamera);
Examples With Parentheses
// Example 1: Use call when executing on a single line alone
...
moveCamera()
...
// Example 2: Use in a loop or an animate() function for repeated calls
// Note: This example is specific to THREE.js
function animate() {
requestAnimationFrame(animate);
moveCamera()
renderer.render(scene, camera);
}