Hi i`m new to JS and I am having a problem with this: My task is to convert this blocking function to a non - blocking function, can you help out?
Original code:
setTimeout(() => console.log('Blocked!'), 1000);
function blocking() {
let a = 0;
for (let i = 0; i < 1000; i++) {
for(let j = 0; j < i * 10000; j++) {
if (i < j) {
a++;
}
}
}
}
blocking();
My first solution, this one is not working at all, not blocking my UI but no console logs of the number a:
function function1()
{
let a=0;
let i=0;
console.log("start");
(function (){
var condition = true;
function codeBlock()
{
if (condition === true)
{
{
for(let j = 0; j < i * 10000; j++)
{
if (i<j)
{
a++;
}
}
}
console.log(a);
if (i<1000)
i++;
else
condition = false;
setTimeout(codeBlock,100);
}
else
{
console.log("done");
}
}
})
}
function1();
My second attempt at solving it: this one isn`t working either, blocking the UI.
let a = 0;
function inner(i)
{
for(let j = 0; j < i * 10000; j++) {
if (i < j) {
a++;
}
}
}
function blocking() {
for (let i = 0; i < 1000; i++) {
setTimeout(inner, i*50,i);
}
}
console.log('Starting!')
blocking();
console.log('Done!')
for(let j = 0; j < i * 10000; j++)that's going to be the issue the higherigetsiapparently has to be smaller thanjso why start from0and not fromi(there is nothing meaningful happening if the condition is not true) For the rest, except for excessively wrapping async calls, the only thing you can really do is execute it in a worker thread, as js is single threaded