Home > OS >  How do i run a function that is nested between two setTimeout()?
How do i run a function that is nested between two setTimeout()?

Time:10-15

Write a function called solution that takes in 2 parameters, a number and a function.

solution should execute the input function (which returns a number) after first input parameter milliseconds. The input function should be run again after waiting the returned number of millisecond

I tried to do it this way but it doesnt work

 const solution = (a,fun) => {
  setTimeout(() => {
    let b=fun();

    setTimeout(() => {
      fun();
    }, b*1000)
  }, a * 1000)
}

It gives me this error:

> node ./node_modules/jest/bin/jest.js -o --watch
 FAIL  js1/__tests__/12.js
  call functions
    × Function should only run twice (5 ms)

  ● call functions › Function should only run twice

    expect(jest.fn()).toHaveBeenCalledTimes(expected)

    Expected number of calls: 1
    Received number of calls: 0

      16 |     // runtime 50ms
      17 |     jest.advanceTimersByTime(50);
    > 18 |     expect(mockFn).toHaveBeenCalledTimes(1);
         |                    ^
      19 |
      20 |     // runtime 100ms
      21 |     jest.advanceTimersByTime(100);

      at Object.<anonymous> (js1/__tests__/12.js:18:20)

CodePudding user response:

The question asks to run it after specific milliseconds but you are multiplying it with 1000 making it run after seconds instead; Removing the 1000 should fix this:

const solution = (a,fun) => {
 setTimeout(() => {
    let b=fun();

    setTimeout(() => {
      fun();
    }, b);
  }, a);
}

solution(1000, () => {
  console.log("Hello");
  return 2000;
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Your code works as is, but it doesn't fulfill the instructions.

after waiting the returned number of milliseconds

You are treating the numbers as seconds, and then multiplying them by 1000 to convert them to milliseconds.

So remove the * 1000 math and it should work as you expect.

  • Related