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 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,209 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
231,275 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.