function throttle(func, delay) {
var timer = null;
var startTime = Date.now();
return function() {
var curTime = Date.now();
var remaining = delay - (curTime - startTime);
var context = this;
var args = arguments;
clearTimeout(timer);
if (remaining <= 0) {
func.apply(context, args);
startTime = Date.now();
} else {
timer = setTimeout(() => {
console.log('duplicate click');
}, remaining);
}
};
}
示例:
$('#screen-btn').on(
'click',
throttle(() => {
if (!TRTC.isScreenShareSupported()) {
alert('当前浏览器不支持屏幕分享!');
return;
}
if ($('#screen-btn').attr('src') == './img/screen-on.png') {
$('#screen-btn').attr('src', './img/screen-off.png');
stopSharing();
isScreenOn = false;
} else {
$('#screen-btn').attr('src', './img/screen-on.png');
startSharing();
isScreenOn = true;
}
}, 2000)
);