-3

I am being given the below mentioned code and asked to print the console after 3 seconds - B and C after A.

I tried

  setTimeout(main(),3000);

But I get no output.

function sleep(){

}

function main(){

console.log('A');

// call after 3 sec
console.log('B');


// call after 3 sec
console.log('C');

}
}
  • _"But I get no output"_ - That's not possible with the script shown (if we ignore the last `}` that shouldn't be there) – Andreas Sep 18 '21 at 07:12
  • Good dupe: https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep – mplungjan Sep 18 '21 at 07:17

6 Answers6

1
setTimeout(main , 3000);

remove function call '( )'

How setTimeout works: You specify the function (as a first argument) to be called after your timeout (second argument: 3000)

Ihar Dziamidau
  • 337
  • 2
  • 9
1

Generally you should pass the function by name to the setTimeout function without calling it.

setTimeout(main,3000);

Lukasz Gawrys
  • 1,234
  • 2
  • 8
1

setTimeout(main(), 3000) will execute main immediately because you put the () after it. Just use the name. setTimeout(main, 3000)

Also, you'll want to put your timeout on the two specific log statements you want to call later, not the whole function, or you could also log A outside of the main function and then call the main function after the timeout.

function main() {

  console.log('A');

  // call after 3 sec
  setTimeout(() => {
    console.log('B');
    console.log('C');
  }, 3000);

}

main();
Liftoff
  • 24,717
  • 13
  • 66
  • 119
1

You are calling the function in the first parameter of setTimeout. It is supposed to be a callback function(function definition). Just copy the code of the main function inside the setTimeout function and it will work.

The setTimeout Function is used usually with two parameters.

  1. The callback function
  2. Time in milliseconds

The callback function is called after a given time (second param).

This is how it is called:

const callbackFunction = () =>{
   console.log("Inside callback");
}

setTimeout(callbackFunction, 2000);

OR simply

setTimeout(() =>{
   console.log("Inside callback");
}, 2000);

Output (after 2 secs)

Inside callback
atiquratik
  • 1,296
  • 3
  • 27
  • 34
masteryong
  • 57
  • 6
1

try this

    setTimeout(main,3000);

  function main(a){
  
      console.log('A');
  
      setTimeout(function(){ 
        console.log('B'); 

        setTimeout(function(){ 
          console.log('C'); 
        }, 3000);

      }, 3000);
   
  }
Bhanu Pratap
  • 144
  • 6
0

Above output could also be reproduced using async-await:

function sleep(time) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("");
    }, time);
  });
}

async function main() {
  await sleep(0);
  console.log('A');

  // call after 3 sec
  await sleep(3000);
  console.log('B');

  // call after 3 sec
  await sleep(3000);
  console.log('C');

}
main();
Paritosh
  • 51
  • 10