setInterval not working with callback function

浪尽此生 提交于 2021-02-08 07:51:55

问题


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

回答1:


In this case

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

the function executes immediately

Use like this

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



回答2:


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



回答3:


Another way is to use following syntax:

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



回答4:


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


来源:https://stackoverflow.com/questions/29698860/setinterval-not-working-with-callback-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!