console.log('This is a demo function');
In this example, we’ve created a function called demoFunction that logs a simple string. The setTimeout method then invokes this function after a delay of 3000 milliseconds, or 3 seconds.
The first argument passed to setTimeout is the function to be executed. The second argument is the delay period in milliseconds. Note that these are the basic parameters and additional ones can be added depending on the complexity of your function.
Remember, setTimeout doesn’t stop the execution of the succeeding code. Therefore, it’s perfectly suited for operations that don’t demand immediate execution like API calls or event handling.
Delving Deeper: The Stack, the Web APIs and the Queue
Caveats and Notes
- setTimeout does not guarantee precise delay. It only ensures a function won’t run before the stipulated time is reached.
- Nested or long-running functions can block the Queue, creating further delay.
- Beware of the ‘this’ keyword in the callback function. It doesn’t refer to the object where setTimeout is declared. To tackle this, use an arrow function or bind the required object to ‘this’.