R2D2
R2D2

Reputation: 2640

Javascript/Jquey - Best way to call two repeating functions to keep set timings

Just now I am using a setInterval in my code, to repeatedly call a function every 5 seconds

setInterval('function1()', 5000);

I know Javascript/jQuery is not particulary accurate on timings, and that is totally fine, but I now want to call another function, approximately half a second before the first function calls again.

So:

0.0s - function1

4.5s - function2
5.0s - function1

9.5s - function2
10.0s - function1

I was thinking about calling function1 on page load, then using setTimeout in function1 to call function2 4.5s after the launch of function1, then calling function1 again using setTimeout from function2.

Is there a better / more efficient way of doing what I need??

The 4.5s and 0.5s times dont need to be particularly accurate, but the separation of the two needs to be reliable and repeatable.

Upvotes: 0

Views: 28

Answers (1)

Mister Jojo
Mister Jojo

Reputation: 22265

may be something like that ?

const 
  delay   = ms => new Promise(r => setTimeout(r, ms))
, function_1 = () => console.log('function 1')
, function_2 = () => console.log('function 2')
  ;
var stop_f1_f2_repeat = false;

async function f1_f2_repeat()
  {
  for (;;) // infinite  loop
    {
    function_1();

    await delay(4500);  // delay in miliseconds == 4.5 s

    if (stop_f1_f2_repeat) break;

    function_2();

    await delay(500);   // delay in miliseconds == 0.5 s

    if (stop_f1_f2_repeat) break;
    }

  console.log('f1, f2 stoped')
  }

btStop.onclick = () => { stop_f1_f2_repeat =  true }

f1_f2_repeat() // infinite loop f1, f2 launch
<button id="btStop"> stop f1, f2 loop</button>

Upvotes: 1

Related Questions