1

Iam making get requests with an interval. On page load i want an interval of 2000, but after 1 get request the interval has to be changed to 20000. What is the best approach in this case ?

$(document).ready(function(){

setInterval(function(){

    $.ajax({

        type: 'GET',
        url : "{% url "messages" object.id %}",
        success: function(response){
            console.log(response);
            $("#display").empty();
            for (var key in response.messages)

                {
                    var temp = "<div class='container manager' style='color:black'><b>" + response.messages[key].werknemer_naam ;
                    
                }

        },
        error: function(response){
            alert('An error occured')
        }
    });
},2000);
})
saro
  • 705
  • 3
  • 13
  • 2
    Make the first delay a setTimeout, then create the setInterval – user2182349 Mar 06 '22 at 21:18
  • Another option is you can save your intervals as variables or push them to an array. Then you can set and clear them by id. – Joe Fitzsimmons Mar 06 '22 at 21:21
  • Just wanted to point out that you got stuck by focusing on the wrong approach. This can be easily solved without changing the intervals delay (which isn't possible anyway). –  Mar 06 '22 at 21:22

2 Answers2

0

You can't change the interval, all you can do is clear it and call setInterval again with the new value. But you can save a bit of code by defining the callback function separately. In your case, I'd probably do this:

function makeRequest() {
  // make the request
}

setTimeout(() => {
  makeRequest();
  setInterval(makeRequest, 20000);
}, 2000);

So it would wait 2000ms, then make the first request and set the request to run every 20000 from then on.

Andrew Taylor
  • 682
  • 4
  • 8
0
  1. Create a boolean set to false outside the setInterval block.
  2. Create another variable w/ the default interval time.
  3. When the first response comes in, set the boolean to true.
  4. With the new true value, the setInterval variable changes to a new value.