如何解决如果在几秒钟内多次调用,则仅对更改事件触发一次警报
我有一个警报,需要在用户更改输入后有条件地向用户显示。我遇到的问题是警报快速按下后连续多次快速触发。我希望警报每隔几秒钟只触发一次。我怎样才能做到这一点?
childElem.on('change',function () {
let currentHeightPaste2k
let scrnwidth
setTimeout(function () {
let actualHeightPaste2k = parseInt($('#' + currenId2c).height()) //Height of DIV
scrnwidth = $(window).width()
if (scrnwidth == parseInt(1226)) {
currentHeightPaste2k = $('#' + currenId2c).get(0).scrollHeight //Content Height of DIV
} else {
currentHeightPaste2k = $('#' + currenId2c).get(0).scrollHeight - 1 //Content Height of DIV
}
if (actualHeightPaste2k < currentHeightPaste2k) {
_.throttle(fireError,300)
CKEDITOR.instances[currenId2c].execCommand('undo')
}
},100)
})
function fireError() {
toast.fire({
type: 'error',title: 'Typing Limit Exceeded',text: 'You have inserted more text than the space will allow.',showConfirmButton: false,confirmButtonClass: 'cancel-btn-class',})
}
解决方法
我认为每次调用回调时您都会创建一个新的节流函数。您应该尝试在更高的范围内创建节流函数,并在回调中使用从 _.throttle
返回的函数。
见https://underscorejs.org/#throttle
,_.throttle
不会调用您传递给它的函数。相反,它返回一个新函数。您需要存储新函数并调用它而不是旧函数。新函数确保旧函数的调用频率不超过您传递给 _.throttle
的时间间隔。以下代码将完成您想要实现的目标(至少就节流而言):
const fireError = _.throtte(function() {
toast.fire({
type: 'error',title: 'Typing Limit Exceeded',text: 'You have inserted more text than the space will allow.',showConfirmButton: false,confirmButtonClass: 'cancel-btn-class',});
},300);
childElem.on('change',function() {
let currentHeightPaste2k;
let scrnwidth;
setTimeout(function() {
let actualHeightPaste2k = parseInt($('#' + currenId2c).height()); //Height of DIV
scrnwidth = $(window).width();
if (scrnwidth == 1226) {
currentHeightPaste2k = $('#' + currenId2c).get(0).scrollHeight; //Content Height of DIV
} else {
currentHeightPaste2k = $('#' + currenId2c).get(0).scrollHeight - 1; //Content Height of DIV
}
if (actualHeightPaste2k < currentHeightPaste2k) {
fireError();
CKEDITOR.instances[currenId2c].execCommand('undo');
}
},100);
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。