crazyfrog
crazyfrog

Reputation: 247

Callbacking a function with arguments

I have an exercise where I have to give three arguments: function and two numbers. The function which I give has to be activated (each) after x miliseconds for y miliseconds. I wanted to make helper like this:

function helper(string) {
  console.log("Printing string which was given: " + string)
}

but when I do it like this and I try to enable my function ex1_4(helper("some string"), 500,5000) I get an error that Callback must be a function What am I doing wrong?

function ex1_4(func, x,y) {
    const resFunction = setInterval((func), x)
    const stop = setTimeout(() => {clearInterval(resFunction)}, y)
}
function helper(string) {
    console.log("Printing string which was given: " + string)

}
ex1_4(helper("some string"),500,5000)

Upvotes: 0

Views: 34

Answers (2)

Rickard Elimää
Rickard Elimää

Reputation: 7591

When you add helper("some string"), you're actually executing the method, instead of sending the method to ex1_4. You should type something like ...

ex1_4(helper,500,5000)  // no parenthesis

... just like you did with setInterval((func), x).

However, you want to add parameters to helper, and in this case, you can use bind. You should really learn about bind(), call(), and apply().

ex1_4(helper.bind(null, "some string"),500,5000)

function ex1_4(func, x,y) {
    const resFunction = setInterval((func), x)
    const stop = setTimeout(() => {clearInterval(resFunction)}, y)
}
function helper(string) {
    console.log("Printing string which was given: " + string)

}

ex1_4(helper.bind(null, "some string"),500,5000)

Upvotes: 0

Slava Knyazev
Slava Knyazev

Reputation: 6081

helper("some string") 

Is a function call which returns a value, in your case it is undefined. If you want to make it into a callback, you need to wrap it in a function like so:

 () => helper(“some string”)

In your code:

ex1_4(() => helper("some string"),500,5000)

Upvotes: 1

Related Questions