Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add intentional latency in express

Im using express with node.js, and testing certain routes. I'm doing this tute at http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/

Im calling the http://localhost:3000/wines via ajax (the content doesn't matter). But I want to test latency. Can I do something like make express respond after 2 seconds? (I want to simulate the ajax loader and I'm running on localhost so my latency is pretty much nil)

like image 806
Tarang Avatar asked Feb 06 '13 20:02

Tarang


3 Answers

Use as middleware, for all your requests

  app.use(function(req,res,next){setTimeout(next,1000)});
like image 66
maggocnx Avatar answered Nov 07 '22 10:11

maggocnx


Just call res.send inside of a setTimeout:

setTimeout((() => {
  res.send(items)
}), 2000)
like image 29
David Weldon Avatar answered Nov 07 '22 11:11

David Weldon


To apply it globaly on all requests you can use the following code:

app.use( ( req, res, next ) => {
    setTimeout(next, Math.floor( ( Math.random() * 2000 ) + 100 ) );
});

Time values are:

Max = 2000 (sort of.... min value is added so in reality its 2100)

Min = 100

like image 7
Playdome.io Avatar answered Nov 07 '22 11:11

Playdome.io