0

I am trying to call a function with setTimeout() inside another function and I keep getting this error:

hi is not defined

This is the code.

hello("hi");
function hello(a)
{
    hi(a);
    function hi(b)
    {
        console.log(b);
        c = setTimeout('hi("' + b + '")', 50)
    }
}

One "hi" is being logged, but then it just stops. I believe problem is in this part: c = setTimeout('hi("' + b + '")', 50)

Is there a fix without changing function inside function structure?

2 Answers2

2

You can pass arguments to function as third argument to setTimeout.

hello("hi");
function hello(a)
{
    hi(a);
    function hi(b)
    {
        console.log(b);
        c = setTimeout(hi, 50,b)
    }
}
Dinesh undefined
  • 5,490
  • 2
  • 19
  • 40
0

c = setTimeout( () => hi(b), 50 ) should work.

Edit (thanks to @evolutionxbox in the comments)

c = setTimeout( hi, 50, b ) looks even better.

You're getting this error :

hi is not defined

at line 4 : hi(a)

The execution is not even making it to the timeout part. The timeout itself won't produce an error, but won't do anything either, because 'hi("' + b + '")' is a string, not a function.

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63