Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript and the DOM (Retiring) Responding to User Interaction Delaying Execution with setTimeout()

Jiten Mehta
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jiten Mehta
Front End Web Development Techdegree Graduate 21,118 Points

Understanding the setTimeout method

Hello!

I'm currently going the the Javascript DOM course and i'm stuck with the setTimeout method.

I'm struggling to understand how the parameters combine in order to execute the method.

My code is below.

window.setTimeout((something) => {
  document.write(something);}
  , 3 * 1000, 'Greetings, everyone');

i'm struggling to understand how the string 'Greetings everyone' gets logged into the console since it is not being passed as an argument to the parameter something.

The method uses a function, delay ( integer ) and a string as parameters.

My current understanding is once the delay parameter has been fired, the argument is passed into the function. However since the string and function are separate parameters, how do they combine in order to log out the message? Hope that makes sense.

Thanks, Jiten.

3 Answers

Steven Parker
Steven Parker
210,475 Points

When you call setTimeout, you're only passing a reference to the function, you're not invoking it. But later, after the time elapses, the code in setTimeout calls the function and the argument is passed to it at that time.

Here's how a version of setTimeout might be implemented that just called the function right away:

define noTimeout(func, ignored, arg) {
    func(arg);    // call the function and pass it the argument
}

With SetTimeOut() the arguments are provided after the delay. So 'Greetings, everyone' will be passed as an argument.