Cleaner setTimeout Callbacks

js_bits_bill

JS Bits Bill

Posted on July 19, 2020

Cleaner setTimeout Callbacks

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

  setTimeout(myFunc, 1000);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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

  setTimeout(myFunc.bind(null, arg1, arg2), 1000);
Enter fullscreen mode Exit fullscreen mode

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} = πŸ”`);
  }
Enter fullscreen mode Exit fullscreen mode

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!

πŸ’– πŸ’ͺ πŸ™… 🚩
js_bits_bill
JS Bits Bill

Posted on July 19, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related