Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

setInterval function

What is the difference between A and B please?

function greet(){console.log("hi")} A- setInterval(greet,500); B- setInterval(greet(),500);

1 Answer

setInterval(greet,500); //runs repeatedly every 0.5 seconds. The timer starts on load.
setInterval(greet(),500); // runs once on load.

When you pass a function with brackets as an argument to another function e.g. `setInterval(greet(), 500) you are passing just the one-time result of the function with the brackets.

When the function is passed as an object reference (without the brackets, only the name of the function) you are passing in what's known as a callback function. See the following vid for more of an idea on callbacks: https://teamtreehouse.com/library/creating-a-simple-callback-function

Some of this answer adapted from: https://stackoverflow.com/questions/15410384/javascript-setinterval-function-with-arguments