1

Here I have a piece of code that auto-executes every 2 seconds. However, the time it takes to execute function roll() varies due to the Internet connection's peaks and bottoms. I'm trying to make the function roll() execute itself automatically every 2 seconds, but the code must wait till the function is fully executed before proceeding and auto-executing again.

P.S. Any suggestions of a better title for this question would be appreciated.

var init = 0.01

var start = init
var $odds = $("#oddsOverUnder")
var $button = $("#roll")
var $bet = $("#bet")

function roll() {
    $bet.val(start)
    $button.click()
    setTimeout(function() {
        var tr = document.querySelector("#myBetsTable tr:nth-child(2)")
        var cls = tr.getAttribute('class')
        if (cls === 'success'){
            start = init
            $bet.val(start)}
        else{
            start = start * 2
            $bet.val(start)
            $odds.click()}
            $button.click();
    setTimeout(function() {
            $button.click();
            },1000);
            },1000);
}

setInterval(roll, 2000)
Recuvan
  • 161
  • 5

3 Answers3

1

Don't use setInterval. It will try to call a function after the elapsed time regardless whether it's finished or not. setTimeout is better, as you can control when it gets called. And you quite normally just call it at the end of a function (where it calls itself).

E.g.

function draw() {
    // Some drawing here...
    setTimeout(draw, 50);
}

So, when you call draw() above, it will do its operations, then wait 50 ms and then call itself again, repeatedly.

See here for further details on the difference.

Community
  • 1
  • 1
ManoDestra
  • 6,325
  • 6
  • 26
  • 50
0

I added setTimeout to the roll function and called it at the end.

var init = 0.01

var start = init
var $odds = $("#oddsOverUnder")
var $button = $("#roll")
var $bet = $("#bet")

function roll() {
    setTimeout(roll, 2000)
    $bet.val(start)
    $button.click()
    setTimeout(function() {
        var tr = document.querySelector("#myBetsTable tr:nth-child(2)")
        var cls = tr.getAttribute('class')
        if (cls === 'success'){
            start = init
            $bet.val(start)}
        else{
            start = start * 2
            $bet.val(start)
            $odds.click()}
            $button.click();
    setTimeout(function() {
            $button.click();
            },1000);
            },1000);
}

roll()
Recuvan
  • 161
  • 5
0

The best would be to do soemething like this:

function roll() {
    var time = Date.now();
    //your stuff goes here
    setInterval(roll, Math.max(2000 - (Date.now() - time)), 1);
}

This tries to optimize tge amount of time between calls, so if the function took 1.5 seconds, then it will fire after 0.5 seconds.

Bálint
  • 4,009
  • 2
  • 16
  • 27