2 回答

TA貢獻1798條經驗 獲得超3個贊
使用去抖動
lodash的去抖動,而不是自己從頭開始編寫。
const debouncedGetPlayerList = _.debounce(get_player_list, 2000);
$('.player-list-control-text').keyup(function(){
debouncedGetPlayerList(); // execute get_player_list after 2s non-interupted
});
現場示例:https ://codepen.io/dcorb/pen/mVGVOL
$(document).ready(function(){
var $statusKey = $('.status-key');
var $statusAjax = $('.status-ajax');
var intervalId;
// Fake ajax request. Just for demo
function make_ajax_request(e){
var that = this;
$statusAjax.html('That\'s enough waiting. Making now the ajax request');
intervalId = setTimeout(function(){
$statusKey.html('Type here. I will detect when you stop typing');
$statusAjax.html('');
$(that).val(''); // empty field
},2000);
}
// Event handlers to show information when events are being emitted
$('.autocomplete')
.on('keydown', function (){
$statusKey.html('Waiting for more keystrokes... ');
clearInterval(intervalId);
})
// Display when the ajax request will happen (after user stops typing)
// Exagerated value of 1.2 seconds for demo purposes, but in a real example would be better from 50ms to 200ms
$('.autocomplete').on('keydown',
_.debounce(make_ajax_request, 1300));
});
body {
background: #444444;
color: white;
font: 15px/1.51 system, -apple-system, ".SFNSText-Regular", "San Francisco", "Roboto", "Segoe UI", "Helvetica Neue", "Lucida Grande", sans-serif;
margin:0 auto;
max-width:800px;
padding:20px;
}
form {
display: inline-block;
padding: 0;
margin: 0;
padding: 5px;
margin: 5px 0 0 0;
}
input {
padding:8px 20px;
border-radius: 2px;
border:0;
font-size:20px;
}
.status-key,
.status-ajax {
margin:10px 0;
}
.status-ajax {
color:#99FF7E;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
<form>
<div class="status-key">Type here. I will detect when you stop typing</div>
<input type="text" class="autocomplete">
<div class="status-ajax"></div>
</form>

TA貢獻1779條經驗 獲得超6個贊
延遲請求直到用戶完成輸入
var timer;
$('.player-list-control-text').keyup(function(){
clearTimeout(timer);
timer = setTimeout(function () {get_player_list();}, 500);
});
500ms 為您節省了很多無用的搜索輸入請求。
- 2 回答
- 0 關注
- 120 瀏覽
添加回答
舉報