2

I want an example of synchronous javascript.

Let's say I have three functions

fun1();
fun2();
fun3();

They all log some data. But I want the second function fun2() to pause the script for 5 seconds and then continue.

Doing setTimeout has not worked as it is async.

krv
  • 2,830
  • 7
  • 40
  • 79
  • This might help you: https://stackoverflow.com/questions/5010288/how-to-make-a-function-wait-until-a-callback-has-been-called-using-node-js – Rajesh Sep 07 '17 at 05:04
  • That's async. I want Synchronous. – krv Sep 07 '17 at 05:04
  • yes. Just for a demo. – krv Sep 07 '17 at 05:07
  • 1
    @krv why do you want to have that synchronous. Even if it would be possible you would completely block the browser window for 5 seconds, which is on the one hand bad for user experience, because the user cannot do anything anymore, and worst of all it also might trigger a long running script warning in the browser, asking the user if the script should be stoped. – t.niese Sep 07 '17 at 05:08
  • 1
    Believe me, you don't *want* to pause everything for 5 seconds. – Bergi Sep 07 '17 at 05:34
  • Just use this two lines of code in ur fun2() and it will work as expected. var dd = new Date().getTime() + 5000; while (new Date().getTime() < dd) {} – Juvenik Sep 07 '17 at 06:02
  • Yes, I Understand async is better but just out of curiosity wanted to know how can this be achieved. – krv Sep 07 '17 at 12:58

2 Answers2

0

Javascript is a single threaded language, so by default, all tasks are synchronous. So func3 will be called after func2.

But if you have any async task inside func2 like setTimeout or XHR, then the sequence will break.

In such cases, you have 2 options, i.e. Callback and Promises.

function func1(){
  var num = 0;
  for(var i = 0; i< 1000; i++){
    num += i;
  }
  console.log('func1: ', num);
}

function func2(){
  var num = 0;
  for(var i = 0; i< 1000000; i++){
    num += i;
  }
  console.log('func2: ', num);
}

function func3(){
  var num = 0;
  for(var i = 0; i< 10000; i++){
    num += i;
  }
  console.log('func3: ', num);
}

func1();
func2();
func3();
Rajesh
  • 24,354
  • 5
  • 48
  • 79
0

Javascript goes out of it's way to avoid blocking the event loop. As such writing a function that purposely blocks the loop for a given time is very unnatural.

Having said that, and only if you promise never to use it for anything other than a demonstrations, you can do something like this:

function fun1(){
  console.log("done in fun1")
  return
}

function fun3(){
  console.log("done in fun3")
  return
}

function fun2(){
  var then = new Date().getTime() + 5000; 

  // wait five seconds the hard way

  while(new Date().getTime() < then) {
  };
  console.log("done in fun2")
  return
}

fun1()
fun2()
fun3()
Mark
  • 90,562
  • 7
  • 108
  • 148
  • 2
    It should additional be mentioned that `while(new Date().getTime() < then){}` will result in a cpu usage of 100% for one core for 5 seconds. – t.niese Sep 07 '17 at 05:37