模拟乱序请求处理

时间:2014-09-11 10:07:18

标签: javascript jquery node.js

我正在尝试模拟setInterval客户端行为,其中ajax GET请求被发送到服务器并且无序返回。例如:

  var ul = $('ul.log'),
            index = 0;

        setInterval(function() {
          var started = new Date(),
              i = index;

              index++;

              $.get('/date', function(date) {
                  var end = new Date();
                  ul.append('<li>Request ' + i + ' started at ' +
                            started.getHours() + ':' + started.getMinutes()
                            + ':' + started.getSeconds());
              });

        }, 1000);

setInterval应该在每个指定的时间间隔后执行,因此如果服务器忙,响应应该按顺序排列。我试图在NodeJS中实现这一方:

var express = require('express');
var app = express();
var i = 0;
app.get('/date', function(req, res){

  var sleep = Math.floor((Math.random() * 5) + 5) * 1000;

  setTimeout(function() {
    res.end("test string");
    i++;
  }, sleep);

});

app.use(express.static(__dirname + '/'));

server = app.listen(3002, function() {
    console.log('Listening on port %d', server.address().port);
});

这里我设置了随机超时,以便不按顺序处理请求。但是,它不起作用(html输出):

Request 0 started at 11:50:6
Request 1 started at 11:50:7
Request 2 started at 11:50:8
Request 3 started at 11:50:9
Request 4 started at 11:50:10

我期待这样的事情:

Request 0 started at 11:50:6
Request 1 started at 11:50:7
Request 4 started at 11:50:10
Request 2 started at 11:50:8
Request 3 started at 11:50:9

我做错了什么?

0 个答案:

没有答案