官术网_书友最值得收藏!

Solution #2 - use a global flag

The solution most people would probably think of first, is using some global variable to record whether the user has already clicked on the button. You'd define a flag named something like clicked, initialized with false. When the user clicks on the button, if clicked was false, you change it to true, and execute the function; otherwise, you don't do anything at all:

let clicked = false;
.
.
.
function billTheUser(some, sales, data) {
if (!clicked) {
clicked = true;
window.alert("Billing the user...");
// actually bill the user
}
}

For more good reasons NOT to use global variables,
read http://wiki.c2.com/?GlobalVariablesAreBad.

This obviously works, but it has several problems that must be addressed:

  • You are using a global variable, and you could change its value by accident. Global variables aren't a good idea, neither in JS nor in other languages.
  • You must also remember to re-initialize it to false when the user starts buying again. If you don't, the user won't be able to do a second buy, because paying will have become impossible.
  • You will have difficulties testing this code, because it depends on external things (that is, the clicked variable).

So, this isn't a very good solution... let's keep thinking!

主站蜘蛛池模板: 合川市| 临安市| 万年县| 铁力市| 定兴县| 平果县| 九龙坡区| 鞍山市| 万宁市| 麻阳| 巴彦县| 淮北市| 彭阳县| 甘南县| 长治市| 沂源县| 蒙自县| 宜兰市| 温泉县| 麻栗坡县| 乐都县| 海林市| 日土县| 福建省| 保山市| 兴文县| 土默特左旗| 阿拉善右旗| 和田市| 秦皇岛市| 柯坪县| 襄城县| 仲巴县| 库车县| 南投市| 安泽县| 台东市| 渭南市| 冕宁县| 吉安县| 鄂伦春自治旗|