在函数完成后10秒重复运行该函数(JavaScript)

Run a function repeatedly 10 seconds after it has completed (JavaScript)

本文关键字:函数 运行 JavaScript 10秒      更新时间:2023-09-26

我有一个函数,它使用"post"从服务器获取数据并进行处理。数据量各不相同,该函数可能需要很长时间(30秒)才能完成。我希望在函数完成上一次迭代后仅10秒重复调用该函数*函数的结果存储在全局中,并在同一函数的下一次迭代中使用。我试过setInterval和setTimeout,但它们似乎都没有给我想要的结果。有什么想法吗?

function foo(){
  $.post( "test.php", { name: "John", time: "2pm" })
      .done(function( data ) {
        // do your stuff with returned data
        // and call itself again...
        setTimeout(foo, 10000);
  });
}  

这种方法不会奏效吗?

function a(){
 //do stuff
 setTimeout(a, 10000); //has to be at the end of the execution. If you're doing things asynchronously that's a different story. 
}

函数setTimeout()可以用于此操作。但是必须第一次调用该方法,然后函数本身再次调用该方法。

    function method(){
         console.log('method invoked');
         setTimeout(method, 10000);
    }
    method();
var $id = 1;
var Interval ;
$(function(){
      callAjax();//Starts Interval
});
functoin callAjax()
{
Interval =   setInterval(function () {
            try {
                if($id > 0)
                {
                $.ajax({
                    url: _MyUrl + $id,
                    success: function (calbkData) {
                        $id = 0;
                        if (parseInt(calbkData.id) > 0) {
                            $id = calbkData.id;
                            OpenMsg(calbkData.id);
                        }
                    },
                    global: false, // this makes sure ajaxStart is not triggered
                    dataType: 'json'
                    //,complete: longpoll
                });
                }
            } catch (e) {
           //     alert(e);
            }
        }, 10000);
}

这对我来说运行得很好。

function Test()
{
  //Your code here
 setTimeout(Test(),10000);
 //Its used to set time interval after your iteration is run
}