[SOLVED] Stop setInterval function with a button

Issue

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

Solution

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.

Answered By – Lucas S.

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.