在for循环中为每个循环创建延迟

时间:2016-01-08 18:54:49

标签: javascript node.js firebase

我希望能够制作console.log(密钥);每隔5秒生成一次日志,此时没有延迟,同时记录所有数据。

//the location of my usres table
  var ref = new Firebase('https://myapp.firebaseIO.com/users/'); 

//ask fire base to get the records just once
    ref.once("value", function (snapshot) {

//loop through the retuned records
    snapshot.forEach(function (childSnapshot) {

// get just the value for the key
        var key = childSnapshot.key();

// log the key - this will be changed to send the value to another function
        console.log(key);

    });
})

上面的console.log给了我成千上万的ID,我需要将这些ID传递给另一个函数,如果我一次性传递所有这些id,则下一个函数将炸毁,所以我想慢慢地将它们传递给下一个功能。欢迎其他想法。

4 个答案:

答案 0 :(得分:1)

使用closurekey

之后获取当前迭代的setTimeout

试试这个:

 var ref = new Firebase('https://myapp.firebaseIO.com/users/');
 ref.once("value", function(snapshot) {
   snapshot.forEach(function(childSnapshot, index) {
     var key = childSnapshot.key();
     setTimeout((function(key) {
       return function() {
         console.log(key);
       }
     })(key), 5000 * index);
   });
 });

答案 1 :(得分:0)

也许你的意思是一个自定义数组迭代器,在指定的延迟后迭代到数组中的下一个元素。我使用函数式编程原理来提高可用性。见下文

/*
 * makeTimedForEach
 *
 * this will create an array itererator that will loop through an array
 * at a specified timeout delay.
 * 
 * @param {array}   arr    array to iterate
 *
 * @returns {Function} function to pass in callback and delay
 */
function makeTimedForEach(arr) {
  return function timedForEach(fn, delay) {
    var ii = 0;
    function iterate() {
      if (ii < arr.length) {
        // call the callback injecting the current element, index and array like native forEach
        fn.call( arr[ii], arr[ii], ii, arr );

        ii++;
        // call iterate again
        setTimeout(iterate, delay);
      }
    }
    // call for the first time you could add a setTimout here 
    // if you needed a delay at the start
    // setTimeout( iterate, delay );
    iterate();
  }
}

// Snapshot mock
function Snapshot(key) {
  this._key = key;
}
Snapshot.prototype = {
  key: function(){
    return this._key;
  }
}


var
  // a mock of the snapshot you get returned from `new FireBase`
  snapshot = [new Snapshot('one'), new Snapshot('two'), new Snapshot('three')],
  // create the iterator
  snapshotTimedForEach = makeTimedForEach(snapshot);

// call the iterator passing in the callback and the delay time
snapshotTimedForEach(function(childSnapshot, ii, arr) {
  console.log( childSnapshot.key(), childSnapshot, ii, arr );
}, 1000);
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>

  

原始答案:

我不确定这是否是你需要的,我不能每5秒记录一次相同的结果。看来你可能想每5秒轮询一次firebase api

var ref = new Firebase('https://myapp.firebaseIO.com/users/');
ref.once("value", function(snapshot) {
  snapshot.forEach(function(childSnapshot) {

    var key = childSnapshot.key();

    // you can use setTimeout that recursively calls itself,
    // setTimeout will run the callback after the time has passed 
    // and wont lock up your thread like setInterval
    function log() {
      console.log(key);
      setTimeout( log, 5000);
    }
    // call log for the first time
    setTimeout( log, 5000);

  });
})

答案 2 :(得分:0)

var ref = new Firebase('https://myapp.firebaseIO.com/users/');

ref.once("value", function (snapshot) {

    for(var i=0; i<snapshot.lenght;i++){
        var childSnapshot = snapshot[i];

        var key = childSnapshot.key();

        setTimeout(function () {
            console.log(key);
        }, 5000); // will stop the loop for 5 seconds every time
    }


});

答案 3 :(得分:0)

你可以像这样使用setTimeout和递归函数:

function values(obj) {
    if (obj instanceof Array) {
        return obj.slice();
    } else {
        return Object.keys(obj).map(function(key) {
            return obj[key];
        });
    }
}

ref.once("value", function (snapshot) {
    var array = values(snapshot.val());
    (function process() {
       var item = array.shift();
       if (item) {
           var key = item.key();
           console.log(key);
           setTimeout(process, 5000);
       }
    })();
});