0

I wish to launch multiples functions at the same time when clicking in a button.

The thing is sensitive since that's launch timers, and if they aren't synchronised the little difference is immediatly visible ...

Actually I use this code :

<button class="btn btn-success startTimer" id="gobutton">Start</button>

    <script type="text/javascript">
        $(".startTimer").click(function() {
            var timeseconds = $("#MoneyTimer").TimeCircles().getTime(); 
            $("#timeseconds").val(timeseconds);
            $("#MoneyTimer").TimeCircles().start();
            $('#totaleuro.compteur1').timer1('start');
            $('#totaleuro.compteur2').timer2('start');
        });
    </script>
WolwX
  • 121
  • 1
  • 15
  • JavaScript is single-threaded, so you cannot do two things "exactly" at the same time. Instead, your functions should use Delta Timing - set `start = Date.now()` and use `Date.now() - start` to determine how long it has been, so you can adjust accordingly. – Niet the Dark Absol Dec 04 '17 at 12:13
  • Possible duplicate of [onclick calling two functions simultaneously?](https://stackoverflow.com/questions/9850689/onclick-calling-two-functions-simultaneously) – Doggo Dec 04 '17 at 12:13

2 Answers2

0

Regular in-browser Javascript is strictly single threaded, hence nothing here will start at the same time. In fact, one of the two functions will only start, if the other finished (or ran into a promise, or...)

You best and only bet is looking into web workers – whose Performance and possible multithreading may vary wildly from implementation to implentation. Still, it's more of a guess, complete parallelness is unguaranteeable. (Also, because processors might have other stuff to do right now...)

Possibly a better solution to your actual problem:

That said, both of your timers could relate to the same starttime, set once and shared in a global variable (or passed in an object).

The will still never run truly in parallel at the same time, but whenever it's their turn (to update display info, metrics, etc...) they will be calculating with relation to the exakt same start-time.

Frank N
  • 9,625
  • 4
  • 80
  • 110
0

You can use setTimeout function. Its callback is executed asynchronously.

<script type="text/javascript">
    $(".startTimer").click(function() {
        var timeseconds = $("#MoneyTimer").TimeCircles().getTime(); 
        setTimeout(function() {$("#timeseconds").val(timeseconds);}, 0);
        setTimeout(function() {$('#totaleuro.compteur1').timer1('start');}, 0);
        setTimeout(function() {$('#totaleuro.compteur2').timer2('start');}, 0);
    });
</script>
pepkos
  • 21
  • 1