Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can ik change the interval of setInterval while running

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading