Jero Lopez
Jero Lopez

Reputation: 398

Emulate blocking function in node.js using Express

In order to test some of the concepts regarding sync vs async functions in node.js I would like to create an example emulating a blocking function, how can I achieve this? More specific, I want to demonstrate that using Express I can implement two GET requests, where the first one blocks the second one when executed in parallel. How should blockingFunctionHere in the following example looks like:

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/1', function(req, res, next) {

  blockingFunctionHere(); // emulate a blocking function for some seconds, let's say 10 seconds

  res.render('index', { title: 'Coming from request #1' });
});

router.get('/2', function(req, res, next) {

    res.render('index', { title: 'Coming from request #2' })
});

module.exports = router;

Upvotes: 1

Views: 356

Answers (2)

nicholaswmin
nicholaswmin

Reputation: 22949

I'd do it using a while loop that checks the time difference between when the function was called vs the current iteration time.

As long as the time difference doesn't exceed a passed delay, keep looping. Since it's a synchronous loop, the Event Loop would be blocked for the duration of the looping.

const block = delay => {
  const now = (new Date()).getTime()
  
  while (((new Date()).getTime() - now) <= delay) {
    // do nothing
  }
}

block(3000) // 3 seconds
console.log('end')

Don't expect this to be time accurate. This emulates, usually unwanted, "blocking" behaviour for around 3 seconds.

Upvotes: 3

Quentin
Quentin

Reputation: 943571

You can create a blocking function by using a loop. Check out much time has passed and let the loop condition pass after 10 seconds.

function blocking() {
    const start = moment()
    let waiting = true;
    while (waiting) {
        const now = moment();
        const time = now.diff(start, "seconds");
        if (time > 10) {
            waiting = false;
        }
    }
}

alert("Before");
blocking();
alert("After");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Upvotes: 2

Related Questions