0
\$\begingroup\$

I have functions nested here in setTimeout

function startWorker (obj) {
  if (!code) {
    return setTimeout(2000, () => {
      startWorker(obj)
    });
  }

  console.log('worker started')
}

How do I correctly use startWorker as the callback without using more functions than needed.

What I'm trying to do:

I'm trying to run the same function with the same argument as the callback to a setTimeout inside without duplicating function calls.

\$\endgroup\$
3
  • \$\begingroup\$ @SᴀᴍOnᴇᴌᴀ I don't understand, this is actual code. \$\endgroup\$ Commented Apr 2, 2020 at 18:42
  • \$\begingroup\$ Okay I have retracted my close vote but bear in mind this tip from The Help center page How do I ask a good question?: "You will get more insightful reviews if you not only provide your code, but also give an explanation of what it does. The more detail, the better." \$\endgroup\$ Commented Apr 2, 2020 at 18:45
  • \$\begingroup\$ Thank you, I'll edit it. \$\endgroup\$ Commented Apr 2, 2020 at 18:49

1 Answer 1

2
\$\begingroup\$

I'm not sure I understand what you're asking, but what if you just use setInterval() instead of setTimeout()?

function startWorker(obj) {
  if (!code) {
    setInterval( () => {
      console.log(obj.action);
    }, 2000);
  }
}

const code = false;
const someObj = {
  action: "tick"
};

startWorker(someObj);

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.