gpt4 book ai didi

jquery - 输入元素火灾更改事件仅在特定时间段后发生一次

转载 作者:行者123 更新时间:2023-12-01 01:00:14 25 4
gpt4 key购买 nike

我想让输入更改在特定时间段后仅触发一次。

在下面的代码中假设我输入了 3 个字符,它会在 1500 毫秒后提醒三次。

我只想提醒一次。

这是我的js代码。

jQuery("#width").on('input',function(){
setTimeout(function(){
alert('hello');
},1500)

});

JSFIDDEL

最佳答案

您将需要去抖功能。要么使用 lodash _.debounce或者自己写一个简单的。然后像这样使用它:

jQuery("#width").on('input', debounce(function() {
alert('hello')
}, 1500))

简单的去抖动函数可能看起来像这样:

function debounce(callback, delay) {
var timeout
return function() {
var args = arguments
clearTimeout(timeout)
timeout = setTimeout(function() {
callback.apply(this, args)
}.bind(this), delay)
}
}

这是一个演示:

jQuery("#width").on('input', debounce(function() {
alert('hello');
}, 1500));

function debounce(callback, delay) {
var timeout
return function() {
var args = arguments
clearTimeout(timeout)
timeout = setTimeout(function() {
callback.apply(this, args)
}.bind(this), delay)
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="width" />

关于jquery - 输入元素火灾更改事件仅在特定时间段后发生一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42554382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com