设置延迟/睡眠/等待在每个动作中执行在nodejs中

时间:2016-12-31 06:01:16

标签: javascript jquery node.js cron scheduled-tasks

我想从数组中分别打印每个字符串,间隔为5秒。但是,目前它在每秒后执行。

            var interval = 5000;
            var index = 0;
            var users = ['12321', '456455', '45665', '45645']

            function printUser() {
                setTimeout(function () {
                    var user = users[index];
                    console.log("Sent To :" + user);
                    index++;
                    if (index < users.length) {
                        printUser();
                    }
                }, interval);
            }

            var when = '00 */1 * * * *';
            var crn = new CronJob(when, function () {

                printUser();

            }, null, true, "GMT");

            crn.start();

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

function printUser(index,interval) {
     setTimeout(function () {
         var users = ['12321', '456455', '45665', '45645'];
         var user = users[index];
         console.log("Sent To :" + user);
         index++;
         if (index < users.length) {
              printUser(index,interval);
         }
     }, interval);
 }

 var when = '* */1 * * * *';
 var crn = new CronJob(when, function () {
       printUser(0,5000);
 }, null, true, "GMT");

 crn.start();