Click here to Skip to main content
15,887,300 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, I am trying to solve the problem below.

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 milliseconds

solution(2000, () => {
  // This function will be run 2000ms after solution is called,
  //   and after that, it will be run after another 3000ms
  console.log('hello')
  return 3000
}) 


What I have tried:

This is my solution currently. Whenever I run the function, it runs function an extra time (I believe from calling func() inside delay). I'm not sure if that is the correct reason the function is running an extra time (printing 'hello' first time before calling the function, then 'hello' 2 times as I believe indicated). What would be the best way to fix this? 

function solution(num, func){
  let delay = func()
  return ()=> {
    setTimeout(func, num);
    setTimeout(func, delay)
  };
}
Posted

1 solution

It calls func up to three times: once when you call it directly:
let delay = func()
and twice more when the timeouts expire:
setTimeout(func, num);
setTimeout(func, delay)

Depending on what func returns the first time, the second timeout may expire immediately (if it returns zero), or it may be some considerable time if a large value is returned.

So I'd start by checking what func actually does in your code ...
 
Share this answer
 
Comments
DesperatelyBadCoder 22-Sep-23 10:23am    
For the purpose of this question/for simplicity, we are just assuming it does return a reasonable number (in this case 3000), but I don't understand how I would use and call the returned number without running the extra console.log as you mentioned when I assign let delay = func()
OriginalGriff 22-Sep-23 11:46am    
Read the question assignment again: it's pretty explicit about what you should do, and it's not what you are doing at the moment!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900