JS Bits with Bill
JS Bits with Bill

JS Bits with Bill

Cleaner setTimeout Callbacks

Cleaner setTimeout Callbacks

JS Bits with Bill's photo
JS Bits with Bill

Published on Jul 19, 2020

1 min read

Sometimes I'll write some code that needs to be wrapped in a setTimeout:

  setTimeout(myFunc, 1000);

If my function took any arguments, it would bum me out by having to add additional lines to call it inside an separate callback:

  setTimeout(() => {
    myFunc(arg1, arg2);
  }, 1000);

To keep things on one line, sometimes I'd bind the arguments to the function this way:

  setTimeout(myFunc.bind(null, arg1, arg2), 1000);

But here's the money: setTimeout takes additional arguments that get passed to the supplied callback:

  setTimeout(myFunc, 1000, '🐄', '🍞'); // Logs "🐄 + 🍞 = 🍔"

  function myFunc(protein, carb) {
    console.log(`${protein} + ${carb} = 🍔`);
  }

So now you can keep your fancy one-liners without binding! 📞

Links

MDN Article on setTimeout


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter!

 
Share this