I am trying to simulate setInterval client side behavior where ajax GET requests are sent to the server and returned back out of order. For example:
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 is supposed to execute after every specified interval, so if the server is busy, responses are supposed to come out order. I tried to implement that side in 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);
});
Here I'm setting random timeout so that requests are processed out of order. However, it doesn't work(html output):
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
and I expected something like this:
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
What I'm doing wrong ?