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

Jiten Mehta
Jiten Mehta
Front End Web Development Techdegree Student 7,943 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
182,438 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
}
Zimri Leijen
Zimri Leijen
6,955 Points

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