Last active
April 27, 2023 15:46
-
-
Save vip3r011/80cdc2194609edbe9a33cda464035147 to your computer and use it in GitHub Desktop.
nodejs blockvsnonblock loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//dont know if this is correct, but leme try, feedback appreciated | |
//blocking: | |
let run = true | |
let count = 0; | |
while(run){ | |
++count; | |
let n = Math.random(); | |
if(n <= 0.01){ | |
run = false; | |
} | |
} | |
console.log(count) | |
//////////////// | |
//vs non blocking | |
let run = true; | |
function isrun(){ | |
return run === true; | |
} | |
function setrun(v){ | |
run = v; | |
} | |
function executeFunctions(checkFunction) { | |
if(!checkFunction()){ | |
return; | |
} | |
let n = Math.random(); | |
if (n <= 0.01) { | |
setrun(false) | |
} | |
if(checkFunction()){ | |
setImmediate(executeFunctions,checkFunction); | |
} | |
else{ | |
return; | |
} | |
} | |
executeFunctions(isrun); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment