random_numbers
random_numbers

Reputation: 33

Js non-blocking function

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!')

Upvotes: 1

Views: 480

Answers (1)

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10157

What do you mean by non-blocking? If you really want a separate thread, you will have to use some sort of a web worker.

If you just want to let your code continue working after function call, you could use setTimeouts.

Just wrap the code you want to continue executing after call stack callbacks are resolved. Something like this should work (bit exaggerated):

function nonBlocking() {
  setTimeout(function() {
    let a = 0;
    setTimeout(() => {
      for (let i = 0; i < 1000; i++) {
        setTimeout(() => {
          for (let j = 0; j < i * 1000; j++) {
            if (i < j) {
              a++;
            }
          }
        }, 0);
      }
    }, 0);
  }, 0);
}

I would also recommend you watch this video:

https://www.youtube.com/watch?v=8aGhZQkoFbQ

Upvotes: 2

Related Questions