您好,我正在开发一个应用程序,我想提高性能。(我知道这个问题有点长 - 我很抱歉。)
我将详细解释它是一个仅使用 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/