How to Pass a Parameter to a setTimeout() Callback
Read this JavaScript tutorial and learn the right way of passing a parameter to a setTimeout() callback. Also, get information about function binding.
The setTimeout function executes code after a specified amount of time. Although it natively accepts extra arguments after the delay, you can also pass arguments to the function using the bind() method:
Javascript setTimeout() callback using the bind method
Note: The standard approach is to pass arguments directly after the delay: setTimeout(valueLog, j * 1000, j). Arrow functions like setTimeout(() => valueLog(j), j * 1000) are also commonly used.
The setTimeout() Method
The <kbd class="highlighted">setTimeout()</kbd> method calls a function and evaluates an expression after a given number of milliseconds. The function is only executed once. To repeat execution, use the setInterval() method. The returned value timeoutID is a positive integer that identifies the timer which is created by the call to the <kbd class="highlighted">setTimeout() </kbd> method. The value can be passed to clearTimeout() to prevent the function from executing.
The bind() Method
The <kbd class="highlighted"> bind()</kbd> method creates a new function which, when called, has its this keyword set to the provided value, with a specified sequence of arguments preceding any provided when the new function is invoked.