javascript Node Js 中每个请求之间的延迟 5 秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12509123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:23:22  来源:igfitidea点击:

delay of 5 seconds between each request in Node Js

javascriptnode.jssetinterval

提问by Kemal Y

Here is my code:

这是我的代码:

I have more than 500,000 records in my database and I want to loop and request some information from another server. I've successfully wrote all functions except delays between each request. If I send all request with node.js remote server goes downs or can not answer each request. So I need to create a queue for looping But my code is not working still sending all request very fast.

我的数据库中有超过 500,000 条记录,我想循环并从另一台服务器请求一些信息。除了每个请求之间的延迟之外,我已经成功地编写了所有函数。如果我使用 node.js 发送所有请求,远程服务器就会宕机或无法回答每个请求。所以我需要创建一个循环队列但是我的代码无法正常工作仍然非常快地发送所有请求。

var http = require('http')
, mysql = require('mysql');
var querystring = require('querystring');
var fs = require('fs');
var url  = require('url');


var client = mysql.createClient({
    user: 'root',
    password: ''
});

client.useDatabase('database');
client.query("SELECT * from datatable",
    function(err, results, fields) {
        if (err) throw err;
        for (var index in results) {
            username = results[index].username;
            setInterval(function() {

                requestinfo(username);
            }, 5000 );

        }
    }
    );
client.end();
}

回答by DeadAlready

Your problem lies in the for loop since you set all the requests to go off every 5 seconds. Meaning after 5 seconds all the requests will be fired relatively simultaneously. And since it is done with setInterval then it will happen every 5 seconds.

您的问题在于 for 循环,因为您将所有请求设置为每 5 秒关闭一次。这意味着 5 秒后所有请求将相对同时地被触发。因为它是用 setInterval 完成的,所以它会每 5 秒发生一次。

You can solve it in 2 ways.

您可以通过 2 种方式解决它。

First choice is to set an interval to create a new request every 5 seconds if the index is a number, so instead of a for loop you do something like:

如果索引是数字,第一个选择是设置一个间隔以每 5 秒创建一个新请求,因此您可以执行以下操作而不是 for 循环:

    var index = 0;
    setInterval(function(){
      requestinfo(results[index].username);
      index++;
    }, 5000)

The second choice is to set all the requests with an increasing timeout so you modify your current script like so:

第二种选择是设置所有请求的超时时间越来越长,这样您就可以像这样修改当前脚本:

    var timeout = 0;
    for (var index in results) {
        username = results[index].username;
        setTimeout(function() {
            requestinfo(username);
        }, timeout );
        timeout += 5000;
    }

This will set timeouts for 0,5,10,15... etc seconds so every 5 seconds a new request is fired.

这会将超时设置为 0,5,10,15... 等秒,因此每 5 秒就会触发一个新请求。