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');
}
}
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)
Generally you should pass the function by name to the setTimeout function without calling it.
setTimeout(main,3000);
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();