【问题标题】:javascript - check a function execution count and make it execute not more than oncejavascript - 检查函数执行计数并使其执行不超过一次
【发布时间】:2018-11-03 06:27:34
【问题描述】:

我使用了一个插件“isInViewport js”,它可以让您知道元素何时在视口中,并让您在发生这种情况时执行某些操作。

所以我写了一个 counting 函数,它是一个数字计数器函数。这会在元素 earn 在视口中时执行。

但是这个counting函数会在每次元素进入视口时开始执行。我希望这个函数执行不超过一次。

这是我编写的代码,运行良好,但与我预期的不同:

$('.earn').on('inview', function (event, visible) {
        console.log('inview');

          if (visible == true) {
        console.log('inview count');

            counting();

          } else {
            $('#counter').text(0);
            $('#counter2').text(0+"$");
          }
        });

我正在寻找的 pusdocode 是:

if(count of function == 0){
  executeFunction();
}
else{

}

有人可以通过 javascript 或 jquery 提供解决方案吗?

【问题讨论】:

  • 创建全局变量为 0。在函数调用时增加它。在函数开始时检查这个变量是否小于必要的限制。
  • jQuery 有one(),但它只执行一次处理程序,否则,使用计数器等。
  • @SergeyKotyushkin 您的解决方案有效。太感谢了!简单易行。 :)
  • @adeneo 我已经尝试过了,但它只适用于像“click”这样的事件处理程序。对我不起作用。但是非常感谢你的回答。 :)
  • @JohnEnosh,但你应该知道全局变量不好)

标签: javascript jquery html function logic


【解决方案1】:

如果您只需要 counting 运行一次,您可以在您的 inview 处理程序中执行类似的操作。

if (visible == true) {
  console.log('inview count');
  if (!this.is_counted) { // 'this' should refer to your element.earn
    counting();
    this.is_counted = true;
  }
}

【讨论】:

  • 非常感谢您的解决方案。我遵循了上面 cmets 中提供的 Sergey Kotyushkin 的解决方案。但是也非常感谢您的解决方案.. :)
  • @JohnEnosh 酷,希望对您有所帮助。
猜你喜欢
  • 2021-12-20
  • 2013-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多