0

User have to see all bets in their dashboard so I created a a function every 2secs that loads all players bet 1 and players bet 2. I want to bind the function to a button so it will STOP running continuously when betting is close and waiting for the outcome and START the function again when the betting is open.

Here's my code:

$(document).ready(function(){
 $("#load_bets1").load("loadbet1.php");
    setInterval(function() {
        $("#load_bets1").load("loadbet1.php");
    }, 2000);
});

$(document).ready(function(){
 $("#load_bets2").load("loadbet2.php");
    setInterval(function() {
        $("#load_bets2").load("loadbet2.php");
    }, 2000);
}); 
crobuz11
  • 3
  • 2
  • Does this answer your question? [Stop setInterval call in JavaScript](https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript) – Reza Saadati Feb 06 '22 at 10:16

1 Answers1

0

setInterval returns an ID that can be passed to clearInterval to stop it.

Example to stop an interval after some time:

let i = 0;
const intervalID = setInterval(() => console.log(i++), 100);
setTimeout(() => clearInterval(intervalID), 1000);

See also the examples at https://developer.mozilla.org/en-US/docs/Web/API/setInterval#examples.

Lucas S.
  • 2,303
  • 1
  • 14
  • 20
  • I can use clearInterval but how can I make it run again after the betting is open again. I have a openBet button where I can put the code for restarting the function. – crobuz11 Feb 06 '22 at 10:24
  • Run `setInterval` again, as you did initially, and store its return value. – Lucas S. Feb 06 '22 at 10:27