How can I pass a parameter to a setTimeout() callback?
setTimeout(function() {
postinsql(topicId);
}, 4000)
You need to feed an anonymous function as a parameter instead of a string, the latter method shouldn't even work per the ECMAScript specification but browsers are just lenient. This is the proper solution, don't ever rely on passing a string as a 'function' when using setTimeout()
or setInterval()
, it's slower because it has to be evaluated and it just isn't right.
UPDATE:
As Hobblin said in his comments to the question, now you can pass arguments to the function inside setTimeout using Function.prototype.bind()
.
Example:
setTimeout(postinsql.bind(null, topicId), 4000);
How do I pass a parameter to a setTimeout() callback?
Since you are missing the parameter in the second form you pass undefined
from the second call on, which will essentially result in a timeout of 4ms (which is the browser minimum).
Use a function wrapper, to safely pass the parameters you need:
function blankWord(t){
console.log('blank!');
setTimeout(function(){blankWord(t)},t);
}
blankWord(5000);
Passing the parameters as third parameters knocks out older IEs, that's why you should not use this until IE8 is dead.
setTimeout pass parameter in for loop
You don't need .bind()
. Either use let
or const
instead of var
...
const $scope = {};
$scope.type = ["st", "ct", "sc", "rm", "bg", "sf", "fl", "sq", "pr", "cr", "vl", "fd"];
for (let i = 0; i < $scope.type.length; i++) {
setTimeout(function () {
console.log("i", i);
// your code
}, i * 2000);
}
How to pass parameters to setTimeout function
use
var timer = setTimeout(function(){
countDown(secs)
},1000);
or
var timer = setTimeout('countDown(' + secs + ')',1000);
In your case the problem was your were using string concatenation with a variable without +
sign (my second example) with will cause a syntactical error
when do setTimeOut callback function get its parameters?
Callback function of the setTimeout
isn't executed until the call stack is empty and the call stack won't be empty until the execution of your synchronous javascript code completes.
As the last statement overwrites the value of x
, when the callback function of setTimeout
is invoked, it logs the latest value, i.e. 7.
It seems that you are expecting the callback function of setTimeout
to be executed while the for
loop is executing BUT that's not how Javascript works.
Once the timer of the setTimeout
expires, callback function of the setTimeout
is enqueued in the task queue. From the task queue, event loop will push this callback on the call stack BUT the callback function won't be pushed on the call stack until no other javascript code is executing, i.e. the call stack is empty.
It doesn't matters how long it takes for the synchronous script execution to end; no scheduled callback will be executed until the synchronous script execution ends.
Keep in mind that all your code executes on a single thread.
Also note that the number of milliseconds passed to setTimeout
is NOT the exact time after which the callback function will be executed; it's the minimum time after which the callback function will be invoked.
SetTimeout function with parameter and without Javascript
setTimout's first parameter is a callback function that will be executed after the timeout. It simply calls the function. It doesn't pass any parameters to it.
The second option is the only one that will work. You'll call createPost(post) and it will push to the array after the timeout that post.
setTimeout function parameters undefined (JS)
You have not passed the parameters to the function callback, when the callback is eventually invoked by the setTimeout
the x
and y
are undefined
.
So you see NaN
as the output because undefined - undefined
is NaN
.
setTimeout
takes the parameters of the function callback you have passed after the delay
argument, in your case after 1000
.
Without passing the parameters, the x
and y
variables is scoped to the function callback. It won't take the values from the outer scope as it is shadowed by the function parameters you have given.
function subtract(x, y) {
setTimeout(function(x, y) {
document.write(x - y);
}, 1000, 1, 1);
}
subtract(1, 1);
Related Topics
How to Access the Matched Groups in a JavaScript Regular Expression
How to Convert an Image into Base64 String Using JavaScript
What Is the Purpose of a Self Executing Function in JavaScript
Cartesian Product of Multiple Arrays in JavaScript
Deleting Array Elements in JavaScript - Delete VS Splice
How to Check If an Object Is an Array
Array.Prototype.Fill() With Object Passes Reference and Not New Instance
How to Get All Properties Values of a JavaScript Object (Without Knowing the Keys)
How to Get the Browser Viewport Dimensions
How to Access Post Form Fields in Express
When Should I Use a Return Statement in Es6 Arrow Functions
Uncaught Referenceerror: $ Is Not Defined
How to Trigger Event in JavaScript
JavaScript: Do I Need to Put This.Var For Every Variable in an Object
JavaScript Equivalent of Python'S Zip Function
How to Check If an Object Has a Specific Property in JavaScript
How May I Reference the Script Tag That Loaded the Currently-Executing Script