JavaScript setTimeout - Interview Question...

setTime-out


By default, all JavaScript code runs synchronously. This means that the statements are evaluated from top to bottom, one after another.


        <script>

            console.log('hello');
            console.log('synchronous');
            console.log('world');

        </script>
       

The strings will be printed to the console in the same order as they appear.


        hello
        synchronous
        world
       


Starting the timer with setTimeout

To delay the execution of some function in JavaScript, you can setTimeout. In the base case it accepts two parameters:

  • callback - the function that should be called
  • delay - in milliseconds

setTimeout sets the timer and calls callback function after delay milliseconds.


The callback function will be executed only once. If you’re looking for repeated execution, you should use setInterval.


        <script>
     
            console.log('hello');

            setTimeout(() => {
            console.log('async message that appears on the screen in 1 second')
            }, 1000);
           
            console.log('world');

        </script>