gpt4 book ai didi

javascript - 如何防止过于频繁地执行 ajax 函数

转载 作者:行者123 更新时间:2023-12-01 03:06:39 24 4
gpt4 key购买 nike

function go_save(){
console.log('saving...');
}

$('button').on('click', function(){
console.log('clicked');
//the above should be written each time the button is clicked
//the next should be executed only if the last click happens 9 seconds in the past
go_save();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>CLICK</button>

go_save 是一个 ajax 函数,我想阻止它在用户一次单击按钮多次时执行。

但我不想等待console.log('clicked'),只想等待go_save()

有什么帮助吗?

最佳答案

您不应该手动执行此操作,我建议您在单击后禁用该按钮,并在 ajax 请求完成后再次启用该按钮。

您可以检查每次单击按钮时的时间差异(以秒为单位)。您可以使用标志变量忽略第一次点击的时间检查:

function go_save(){
console.log('saving...');
time = new Date();
isFirst = false;
}
var time = new Date();
var isFirst = true;
$('button').on('click', function(){
console.log('clicked');
//the above should be written each time the button is clicked
//the next should be executed only if the last click happens 9 seconds in the past
var diff = (new Date().getTime() - time.getTime()) / 1000;
if(isFirst || diff >= 9)
go_save();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>CLICK</button>

关于javascript - 如何防止过于频繁地执行 ajax 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60900453/

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