pratik
pratik

Reputation: 119

What is the correct way to pass parameters to function in JavaScript?

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

Answers (3)

jbabey
jbabey

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

Phil Booth
Phil Booth

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

Matías Fidemraizer
Matías Fidemraizer

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

Related Questions