Welcome to ciysys blog

Javascript - Immediately Invoked Function Expression (IIFE) firing timing

Published on: 15th Apr 2024

Overview

JavaScript does not allowed to use await keyword in a function that has not been marked with async. To overcome this limitation, we will have to use Immediately Invoked Function Expression or IIFE in short.

A sample program will be worth more than a thousand words in showing the firing timing. Let's dive into the code

Sample program

The following is the sample code to see the IIFE firing timing.

console.log('start..');

function proc1() {
    console.log('this is proc 1');
}

// this will be run in the next cycle
setImmediate(async () => {
    console.log('setImmediate runs an async fn');
});

var i = 0;

// this will be run in the next cycle
async function proc2() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(`  proc2 runs after 500ms..i=${++i}`);
            resolve();
        }, 500);
    });
}

// this runs immediately before calling proc1().
(async () => {
    console.log('async iife - immediately-invoked function expression, run');

    // the following line will block the execution
    // and continue next line upon completion.
    await proc2();
    await proc2();

    console.log('async iife - exit');
})();

proc1();

console.log('script file last line');

Here's the output of the above program:

start..
async iife - immediately-invoked function expression, run
this is proc 1
script file last line
setImmediate runs an async fn
  proc2 runs after 500ms..i=1
  proc2 runs after 500ms..i=2
async iife - exit

Conclusion

JavaScript program is running in libuv and provides an event loop for executing the synchronous code, timer and async codes. Some times, it is confusing and your program might work unexpectedly. As a result, it is better to write some simple program for reviewing the firing timing.

Jump to #JAVASCRIPT blog

Author

Lau Hon Wan, software developer.