因此,我正在尝试编写一个将每1小时执行一次的计时器。第一个setInterval
应该从Web API获取项目列表,然后下一个计时器将每秒执行一次,在该计时器中,您将单独检查每个项目,并在需要时进行另一个查询。该第二个计时器将在到达列表末尾时结束,并且在下一个第一个setInterval
执行时将在下一个小时再次开始。为什么我首先需要2个计时器?好吧,简单地说,我需要第二个不要打破API查询限制。
我对此的看法是这样的:
setInterval(function ()
{
var counter = 0;
var returnCode;
var getUrl = "url";
returnCode = httpGet(getUrl);
var object = JSON.parse(returnCode);
function httpGet(url){
var response = requestSync(
'GET',
url, (err, res, body) => {
if(err)
{
return;
}
});
return response.body;
}
setInterval(function ()
{
//Do some more stuff with data here
if(!object || typeof object.data[counter] === 'undefined')
{
return; //this should end the second setInterval until the first one is activated again
}
counter++;
}, 1000);
}, 3600000);
我知道它不是那样工作的,因为计数器是一个局部变量,列表也是一个局部变量,但是我不知道如何使它工作。有什么想法吗?
答案 0 :(得分:1)
setInterval(function ()
{
var counter = 0;
var returnCode;
var getUrl = "url";
returnCode = httpGet(getUrl);
var object = JSON.parse(returnCode);
function httpGet(url){
var response = requestSync(
'GET',
url, (err, res, body) => {
if(err)
{
return;
}
});
return response.body;
}
let isFinished = true;
let ref = setInterval(function ()
{
// if the current iteration is taking longer than 1 second then just return;
if(!isFinished){
return;
}
isFinished = false
//Do some more stuff with data here and once it is done make isFinished = true
isFinished = true;
counter++;
if(!object || typeof object.data[counter] === 'undefined')
{
return clearTimeInterval(ref);
}
}, 1000);
}, 3600000);
答案 1 :(得分:1)
您可以使用clearInterval
停止第二个循环。
/**
* Perform a GET request and returns JSON body
*/
function httpGet(url) {
const response = requestSync(
'GET',
url,
(err, res, body) => {
if (err) {
return;
}
});
return JSON.parse(response.body);
}
setInterval(function() {
let counter = 0;
// Execute one request
const returnCode = httpGet('url');
const descriptor = setInterval(function() {
//Do some more stuff with data here
if (!object || typeof object.data[counter] === 'undefined') {
// Stop the second setInterval
clearInterval(descriptor);
return;
}
counter += 1;
}, 1000);
}, 3600000);