JavaScript SetTimeout

PHOTO EMBED

Thu Jun 30 2022 14:11:25 GMT+0000 (Coordinated Universal Time)

Saved by @Polly

function getUsers() {
  let users = [];
  // Fake an async call 
  setTimeout(() => {
    users = [
      { username: 'john', email: 'john@test.com' },
      { username: 'jane', email: 'jane@test.com' },
    ];
  }, 1000);
  return users;
}

function findUser(username) {
  const users = getUsers(); // call Fake API async 
   // executes syncronously - will look for users before setTimeout has completed.
  const user = users.find((user) => user.username === username);
  return user;
}

console.log(findUser('john'));

/** 
*  invoking a fucntion w/ setTimeout will execute the next line of the calling function w/o waiting for setTimeout to complete
*  using the callback technique implements a delay that would alot some time for setTimeout to complete
*/


*********************
// callback = (users) => return userFound=user
function getUsers(callback) {
  setTimeout(() => {
    // pass in data from src = API, File, In-Memory, etc...
    callback([
      { username: 'john', email: 'john@test.com' },
      { username: 'jane', email: 'jane@test.com' },
    ]);
  }, 1000);
}

// pass a function to getUsers = (users) => users.find
// that function is the callBack in getUsers definition
// it's argument is the data from some source
// it retunrs the data after 1 second in this case
function findUser(username, callback) {
  getUsers((users) => {
    const user = users.find((user) => user.username === username);
    callback(user);
  });
}
// console.log is invoking the callback in this case 
findUser('john', console.log);
Code language: JavaScript (javascript)
content_copyCOPY

https://codepen.io/paarudeneesu/pen/rNdaYPr?editors=1011

https://www.javascripttutorial.net/es6/javascript-promises/