javascript - 统计一秒钟内鼠标点击的次数

标签 javascript qt qtscript

您好,我正在开发一个应用程序,我想提高性能。(我知道这个问题有点长 - 我很抱歉。)

我将详细解释它是一个仅使用 qtscript/qscript(有点 javascript)而不使用 html 的出价应用程序。

当用户单击按钮时,我想指向一个文本字段(对于普通用户来说,每秒单击 -1 或 2 次就可以了)。但是用户疯狂地点击按钮(每秒 5 -10 次点击 - 是的,有些人就是这样点击的),它降低了性能,比如显示数量需要延迟,因为每次点击都指向文本字段。

我正在考虑一些解决办法,比如如果用户在 1 秒内点击超过 3 次,我们仅在最后一次点击后调用焦点函数 - 我不知道这是一个正确的解决方案,如果你们知道更好的事情请建议。另一个问题是我无法使用 setInterval() 和clearInterval()。

任何帮助将不胜感激。

最佳答案

我会看一下 Underscore.js_.throttle 函数。

_.throttle = function(func, wait, options) {
  var context, args, result;
  var timeout = null;
  var previous = 0;
  options || (options = {});
  var later = function() {
    previous = options.leading === false ? 0 : new Date;
    timeout = null;
    result = func.apply(context, args);
  };
  return function() {
    var now = new Date;
    if (!previous && options.leading === false) previous = now;
    var remaining = wait - (now - previous);
    context = this;
    args = arguments;
    if (remaining <= 0) {
      clearTimeout(timeout);
      timeout = null;
      previous = now;
      result = func.apply(context, args);
    } else if (!timeout && options.trailing !== false) {
      timeout = setTimeout(later, remaining);
    }
    return result;
  };
};

它看起来确实很复杂,但一个基本的例子是:

var func = function(){alert("Only do this once every second");},
    throttled = _.throttle(func, 1000);

// Call func() three times in under a second, and
// you get 3 message boxes
func(); // alerts
func(); // alerts
func(); // alerts

// Call throttled() three times in under a second, and
// you only get a message box the first time
func(); // alerts
throttled(); // does nothing
throttled(); // does nothing

// ... wait >1 second ...
func(); // alerts
throttled(); // does nothing
throttled(); // does nothing

关于javascript - 统计一秒钟内鼠标点击的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18152433/

相关文章:

c++ - 访问 QScriptEngine 在堆上创建的值?

javascript - ExtJS 5.0 - 覆盖以在网格列上提供自定义排序

javascript - 如何将两个一维频率分布图放在一起?

c++ - QRegularExpressionMatch内存消耗

c++ - 处理导出到 QtScript 的函数中抛出的 C++ 异常

c++ - QML 访问不可调用函数

php - WordPress 仪表板上的自定义内容

javascript - 为什么我无法在 Angular 5 和 TypeScript 中使文本区域部分不可编辑?

c++ - 在 Windows 中部署 Qt 应用程序

c++ - 将 SQLite 数据库中的数据保存到变量中