json2021
json2021

Reputation: 2317

setInterval not working with callback function

I am trying to use the setInterval to call a function that will load orders using ajax. However when I pass in a argument to the call back, the setInterval function stops working. W

hen I don't pass in any arguments it starts working .

Any ideas on how I can make it work with arguments? Below is my code

Thank you in advance!

function httpGetRequest(page){
        $.get(page)
        .done(function(data){
              $(".display_orders").html(data);
        });
}
setInterval(httpGetRequest('load_orders.php'), 30000);

Upvotes: 3

Views: 7059

Answers (4)

CJT3
CJT3

Reputation: 2908

Whenever you use setInterval or setTimeout be sure to give it a variable name so that you can cancel it if you need to.

var orderInterval = setInterval(function(){httpGetRequest('load_orders.php');}, 30000);

In the event that you want to stop it you are now able to call:

clearInterval(orderInterval);

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74420

Another way is to use following syntax:

setInterval(httpGetRequest, 30000, 'load_orders.php');

Upvotes: 0

sudhansu63
sudhansu63

Reputation: 6190

Also you can call like this.

function myFunction()
{
httpGetRequest('load_orders.php');
}

function httpGetRequest(page){

        $.get(page)

            .done(function(data){
                $(".display_orders").html(data);
            });


}

setInterval (myFunction, 30000);

Upvotes: -1

Sudharsan S
Sudharsan S

Reputation: 15393

In this case

setInterval (httpGetRequest('load_orders.php'), 30000);

the function executes immediately

Use like this

setInterval ( function() { 
     httpGetRequest('load_orders.php')
 }, 30000);

Upvotes: 9

Related Questions