我有以下代码:
$("#test").on("keyup", (e) => {
if(e.target.value.length === 3) {
setTimeout(() => {
console.log("fired")
}, 2000)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test">
如果用户输入 3 个字符,console.log("fired")
会在 2 秒后自动触发(适用于上述代码)
但是如果用户在这段时间内输入另一个字符,我需要能够清除旧的超时并再次等待 2 秒。
一旦超时,它应该会按预期运行。我怎样才能做到这一点?
编辑:
let timeOut;
$("#test").on("keyup", (e) => {
if(e.target.value.length === 3) {
timeOut = setTimeout(() => {
console.log("fired if length is 3")
}, 2000)
} else if (e.target.value.length === 4) {
clearTimeout(timeOut)
timeOut = setTimeout(() => {
console.log("fired if length is 4")
}, 2000)
}
})
最佳答案
存储对超时的引用,然后您可以在再次触发创建超时时使用引用和函数 clearTimeout 重置它。
您还可以存储一个标志来跟踪消息是否已被触发,并使用此标志来中止进一步的操作。
let timeOut,
hasFired = false;
$("#test").on("keyup", (e) => {
if ( hasFired ) {
return;
}
if(e.target.value.length >= 3) {
clearTimeout( timeOut );
let message = "length is " + e.target.value.length;
timeOut = setTimeout(() => {
console.log( message );
hasFired = true;
}, 2000)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test">
关于javascript - 在用户输入上使用 setTimeOut 来触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51471217/