Coding Diary: JavaScript Learning Log 4

gravatar
By Ranti
 · 
February 8, 2023
 · 
2 min read

Coding diary to reflect concepts that I am learning and revisiting

Asynchronous callback functions like setTimeout are functions that don't run immediately but sometime in the future

For example

setTimeout(() => {
	console.log("One second later")
}, 1000);
/*
syntax:
setTimeout(() => {
	// code
}, milliseconds);
*/
JavaScript

JavaScript always runs top to bottom. So even when an asynchronous callback function runs it means that there is a delay. It is "queued up" for the future.

console.log("Here!");
setTimeout(() => {
	console.log("I'm next!")
}, 1000);
console.log("No, I want to be next! You're delayed");

/*
Output order:

Here!
No, I want to be next! You're delayed
I'm next (shows up one second later)

*/
JavaScript
  • The success callback is an asynchronous callback that will run when the function has finished its task
  • Callbacks exist for perfomance reasons it allows other pieces of code and schedule other pieces of code for the future

Examples of callback functions in use:

import {welcome} from "./helpers.js";

/**
 * @param {string} name
 */
const sayHello = (name) => {
    welcome(name, () => {
        console.log("Finished!");
    });
}
// sayHello("Jim");
JavaScript
  • Here the function welcome accepts a parameter called "name"
  • The function welcome() will be executed after which it will print "Finished!"

welcomeUser("Sam", () => {
    console.log("Done welcoming user");
});
JavaScript

Concepts Reviewed

  • Setters and getters
  • Method chaining with return this
  • Callback functions
View