Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在函数完成10秒后重复运行函数(JavaScript)_Javascript_Jquery - Fatal编程技术网

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

在函数完成10秒后重复运行函数(JavaScript),javascript,jquery,Javascript,Jquery,我有一个函数,它使用“post”从服务器获取数据并进行处理。数据量各不相同,功能可能需要很长时间才能完成(30秒)。我希望函数能够被重复调用,但只在它完成上一次迭代后10秒*函数的结果存储在全局函数中,并在同一函数的下一次迭代中使用。 我尝试过setInterval和setTimeout,但这两种方法都没有给出我想要的结果。 有什么想法吗?函数setTimeout()可用于此。但是必须第一次调用该方法,然后函数本身再次调用该方法 function a(){ //do stuff setTi

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

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

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. 

}
    function method(){

         console.log('method invoked');
         setTimeout(method, 10000);
    }

    method();
这种方法不管用吗

function Test()
{
  //Your code here

 setTimeout(Test(),10000);
 //Its used to set time interval after your iteration is run

}

这对我来说非常好。

为什么setInterval不能提供所需的输出?你能解释一下吗?给我们看看你的代码,这样我们就能知道发生了什么ob@taesu当涉及Ajax请求时,interval将不起作用。OP希望通话结束并处理完毕后10秒。欢迎来到。请注意,已经有多个答案说明了相同的问题,并且由于函数中立即调用了
Test
,因此此代码无法正常工作。
function Test()
{
  //Your code here

 setTimeout(Test(),10000);
 //Its used to set time interval after your iteration is run

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