Search code examples
javascriptfunctionecmascript-6argumentssettimeout

Send property as argument in function


I have a bootstrap alert that is being called a few different times so I want write a function to reuse. I want the alert to disappear after 3 seconds and also do something. So in my setTimeout I want to do things like location.reload() or textbox.value="".

My code:

const alerts = (msg, todo) => {
  alert.classList.remove("d-none");
  document.getElementById("msg").innerHTML = msg;
  setTimeout(() => {
    alert.classList.add("d-none");
    todo;
  }, 3000);
};

alerts("message1", location.reload());
alerts("message2", (textbox.value=""));

My second argument is not being called. Hoe do I fix that?


Solution

  • As Sergey suggested in the comments, you can use callback function to achieve what you are trying to do.

    Anything that you provide as part of the callback will be executed when todo() is called in the alerts function.

    Example:

    const alerts = (msg, todo) => {
      console.log(msg)
      setTimeout(() => {
        todo();
      }, 3000);
    };
    
    alerts("message1", () => {
      //location.reload()
      console.log("message 1 callback")
    });
    
    alerts("message2", () => {
      //textbox.value = ""
      console.log("message 2 callback")
    });