Reputation: 119
In my javascript code i have the following:
function foo(param1) {
setInterval( bar(param1), 3000 );
}
function bar(msg) {
alert(msg);
}
function set() {
foo('hello');
}
And on page load i call set()
, it gives the alert message only once. Why it does not work as i would expect.? I think the problem is with the parameter that i am passing the foo()
function, but what it is exactly, i am not able to figure out.
If the problem is with the parameter, what can be an alternate way to achieve the desired result.?
Thanks.
Upvotes: 1
Views: 199
Reputation: 46647
You need to pass a function to setInterval
, you are executing a function and passing it's return value (undefined
since the function executed does not have a return value).
Try using an anonymous function instead:
function foo(param1) {
setInterval(function () {
bar(param1);
}, 3000);
}
function bar(msg) {
alert(msg);
}
param1
never changes here, so there is no need for anything more complicated. Here's a working example.
Upvotes: 1
Reputation: 4913
The best way is to use a closure to access the parameter from a function that you pass to setInterval
:
function foo(param1) {
setInterval(function () {
bar(param1);
}, 3000);
}
function bar(msg) {
alert(msg);
}
function set() {
foo('hello');
}
Upvotes: 2
Reputation: 64943
setInterval
expects a function while you're giving the return value of calling the whole function.
A modified version that should work:
var msg = null;
function foo(param1) {
// When foo is called, its argument is set to msg variable, so the function called
// by setInterval will have access to the message that must show in a window.alert
msg = param1;
setInterval(bar, 3000 );
}
function bar() {
alert(msg);
}
function set() {
foo('hello');
}
Upvotes: 1