I am working through a tutorial here and have encountered some syntax that I don't fully understand.
I want it to be that every time I scroll, console.log logs "hello".
function moveCamera() {
console.log("hello");
}
document.body.onscroll = moveCamera()
function moveCamera() {
console.log("hello");
}
document.body.onscroll = moveCamera
In the first example, console.log("hello") runs once, but then never again, regardless of my scrolling.
In the second example, the code runs and logs "hello" every time there is a scroll.
I understand that for the second example, moveCamera passes a copy of the function, making a function that looks somewhat like this:
document.body.onscroll = function () {
console.log("Hello");
}
However, I still don't understand why calling moveCamera() with parenthesis doesn't work and yields undesired functionality.
EDIT: I devised a pretty easy way to understand when to use parenthesis and when not to. I'll put it here since my question was labelled duplicate.
Without Parenthesis Examples
// Example 1: If you are assigning, use reference
document.body.onscroll = moveCamera;
// Example 2: If you are event listening, use reference
document.body.addEventListener("scroll", moveCamera);
With Parenthesis Examples
// Example 1: If you are executing on a single line alone, use call.
...
moveCamera()
...
// Example 2: If you want to repeatedly call this function,
// like I did in my example, use a loop or an animate() function.
// @note this is a THREE.js specific example
function animate() {
requestAnimationFrame(animate);
moveCamera()
renderer.render(scene,camera);
}