You can pass arguments into setTimeout and setInterval
Let's say you want to pass 2 variables to the function you call in setTimeout.
Approach 1
var callback = function(a, b){
console.log(a + b); // 'foobar'
};
window.setTimeout(function(){
callback('foo', 'bar');
}, 1000);
Approach 2
window.setTimeout(callback, 1000, 'foo', 'bar');
(Approach 2: IE Support > 9)
Written by Brian
Related protips
1 Response
Another approach is to use bind method of functions:
window.setTimeout(callback.bind(null, 'foo', 'bar'), 1000);
And it is working in IE since 9 version and you can grab polyfill at MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#