Time Controlled Yelding
JS
S
JavaScriptSnippet to control yelding to achieve a balanced performance level. /!\ Please note that an offloading solutions comes to mind (like forking a child process) but this comes with the downside of passing, managing and processing serialized data back and forth as the offloaded code can’t access the context of the main (and only) JS thread
1// For the bash liveness prob: `while true; do date && curl -m 5 http://localhost:3000/health && echo; sleep 1; done`
2var express = require('express');
3var router = express.Router();
4
5// Phase 5 of Event Loop Stack
6const unblockWithSetImmediatePromise = () => {
7 return new Promise((resolve) => {
8 setImmediate(() => resolve());
9 });
10}
11
12
13async function calculatePrimesBlocking(iterations, multiplier) {
14 let blockingSince = Date.now()
15 var primes = [];
16 for (var i = 0; i < iterations; i++) {
17 var candidate = i * (multiplier * Math.random());
18 var isPrime = true;
19 for (var c = 2; c <= Math.sqrt(candidate); ++c) {
20 if (candidate % c === 0) {
21 isPrime = false;
22 break;
23 }
24 }
25 // Check for blocking 1/2s
26 if ((Date.now() - blockingSince) > 500) {
27 blockingSince = Date.now();
28 await unblockWithSetImmediatePromise();
29 }
30 if (isPrime) {
31 primes.push(candidate);
32 }
33 }
34 return primes;
35}
36
37
38/* GET home page. */
39router.get('/', async function(req, res, next) {
40 const result = await calculatePrimesBlocking(Math.pow(2,16), 10000);
41 console.log('result', result);
42 res.sendStatus(200);
43});
44
45router.get('/health', function(req, res, next) {
46 res.sendStatus(200);
47});
48
49module.exports = router;Created on 2/17/2019