DEV Community

Cover image for Cleaner setTimeout Callbacks
JS Bits Bill
JS Bits Bill

Posted on • Edited on

4 1

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!

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay