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
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#