Pass a parameter into a function setting a setTimeout?

Is there a way I can call this from another module specifying the timeout in brackets?

var addActiveDiv = () => {
  var activeEl = document.querySelector(".o-wrapper");
  setTimeout(() => {
    activeEl.classList.add("is-active");
  }, 1850);
}

addActiveDiv();

export { addActiveDiv }

Something like

addActiveDiv(2000); where 2000 is the new timeout?

2 answers

  • answered 2019-07-10 21:56 Snow

    Just specify the function as taking a parameter, and pass that parameter to setTimeout?

    var addActiveDiv = (ms) => {
      var activeEl = document.querySelector(".o-wrapper");
      setTimeout(() => {
        activeEl.classList.add("is-active");
      }, ms);
    }
    
    addActiveDiv(2000);
    
    export { addActiveDiv }
    

  • answered 2019-07-10 22:03 Stanislav Zaleski

    Use parameters or default parameters.

    var addActiveDiv = (timeout = 1850) => {
      var activeEl = document.querySelector(".o-wrapper");
      setTimeout(() => {
        activeEl.classList.add("is-active");
      }, timeout);
    }
    
    addActiveDiv();
    
    export { addActiveDiv }
    
    import { addActiveDiv } from "foobar";
    
    addActiveDiv(2000);