• Design
  • Shotty
  • Blog
  • Reading
  • Photos
Menu

Jacob Ruiz

Product Designer
  • Design
  • Shotty
  • Blog
  • Reading
  • Photos
before@2x.png

How to Limit The Number Of Times A Function Can Be Called in Javascript

May 30, 2018

Imagine we define a function that returns the time:

var sayTime = function() {
    return Date.now()
};

Calling this function will always give us the present time (expressed in the number of milliseconds elapsed since January 1, 1970).

sayTime();
// 1527745490828

sayTime();
// 1527745493242

sayTime();
// 1527745494395

With Underscore's before function we can create a new version of this function that is can only be called a certain number of times.

var sayTimeLimited = _.before(3, sayTime);

// First call
sayTimeLimited();
// 1527745553103

// Second call
sayTimeLimited();
// 1527745557316

// Third call (and beyond) will return the memoized result of the previous call.
sayTimeLimited()
// 1527745557316

Follow @JacobRuizDesign
← How Underscore's mapObject WorksTutorial: How To Create a Range Of Numbers with Underscore.js (includes video) →
shotty-skinny2x.jpg

Shotty - Faster Access To Your Screenshots on Mac

Shotty is an award-winning Mac app I created to give you instant access to all your recent screenshots, right from the menu bar. You can even add annotations on-the-fly. Stop wasting time digging through Finder for your screenshots. I promise it’ll change your workflow forever (just read the App Store reviews!).



Most popular

information-architecture

Information Architecture: The Most Important Part of Design You're Probably Overlooking

Follow @JacobRuizDesign