Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

305
Views
How do i run a function that is nested between two setTimeout()?

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)
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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;
});

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!