Solution 3 – removing the handler

We may go for a lateral kind of solution, and instead of having the function avoid repeated clicks, we might just remove the possibility of clicking altogether. The following code does just that; the first thing that billTheUser() does is remove the onclick handler from the button, so no further calls will be possible:

function billTheUser(some, sales, data) { document.getElementById("billButton").onclick = null;  window.alert("Billing the user...");  // actually bill the user}

This solution also has some problems:

  • The code is tightly coupled to the button, so you won't be able to reuse it elsewhere.
  • You must remember to reset the handler, otherwise, the user won't be able to make a second buy.
  • Testing will ...

Get Mastering JavaScript Functional Programming - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.