Penalty function when the countdown is 0. In one case, when all four countdowns are 0, the ajax() method will be triggered at the same time. In this case, I only want to trigger it once. What should I do?
I have tried to declare a count to count, and the ajax() method will not be executed if it exceeds 1. However, it is possible that the subsequent countdown will not be executed because it does not satisfy the logic that the count does not exceed 1. What should I do?
html
<span class="clock">4:00</span>//倒计时是循环的,到0后恢复为4分钟,其他一样
<span class="clock">3:00</span>
<span class="clock">2:00</span>
<span class="clock">1:00</span>
js
$('.clock').each(function(elem,index){
$(this).on('finish',function(){//倒计时为0时触发ajax()方法
ajax();
});
});
大家讲道理2017-06-12 09:25:23
JS is single-threaded so it will not be triggered at the same time. You can maintain a variable to record the time when the function was last executed. If the interval is too close, it will not be executed a second time.
伊谢尔伦2017-06-12 09:25:23
Define a variable as the request status. The default is false, which means there is currently no request. Before the request is started, check whether it is true. If it is, it means that the last request is not continuing. Otherwise, set it to true and start executing the request. Ajax's complete method Set to restore the status to false regardless of success or failure so that it will be available for the next request. That is, use a global or local variable to control state.
漂亮男人2017-06-12 09:25:23
Try this:
let loading = false
$('.clock').each(function () {
$(this).on('finish', function () {
if (loading) return
loading = true
ajax({
finish: function () {
loading = false
}
})
})
})