Answer the question
In order to leave comments, you need to log in
How to make settimeout work with the desired value?
I'm creating a search, when a keyboard key is clicked, the keyup event fires in the initialize function. It receives the value of the field where the search string is entered and it is sent to the server using the send function. But before sending a request to the server, you need to check whether the value in the field has changed after 800ms. This cannot be done. the variable is constantly overwritten and I compare the same value several times in the end (if you reduce it to 1ms, then everything is ok). I need settimeout to check the value that I once passed against the current one. But this does not happen, if you quickly print, then in these 800 ms it will overwrite the variable many times and the wrong value will be checked. I tried to do stacks and what did not try. Help))
I thought that passing a value to settimeout would work fine, but no ((
var ajax = require('./ajax.js'),
query = require('./query.js');
//global variablse;
var mainBox = $('.search-fild'),
fild = mainBox.children('.main-search'),
result = mainBox.children('.result-search'),
sbtn = mainBox.children('.input-group-btn').children('button'),
black = mainBox.children('.black');
function initialize(){
/*
Инициализирует search модуль на странице
*/
//INPUT
fild.keyup(function(){
var value = $(this).val();
result.children('.result-item').remove();
send(value);
});
}
function renderResultItems(data){
for(var i = 0, l = data.length; i<l;i++){
result.append('<div class="result-item"> ( '+data[i].ID+' ) '+data[i].COMENT+' </div>');
}
}
function send(val){
if(val.length>=3){
console.log('[send] val:'+val);
setTimeout('time( "'+val+'" )',800);
}else{
result.children('.result-item').remove();
}
}
window.time =function(val){
console.log('[time] val:'+val+' fildval:' + fild.val());
if(val===fild.val()){
ajax.search(val);
}
};
module.exports.init = initialize;
module.exports.renderItems = renderResultItems;
Answer the question
In order to leave comments, you need to log in
Насколько я понял, нужно сделать отправку не чаще, чем раз в 800мс и только если значение изменилось, тогда примерно так:
var lastsend, lastval, timer;
var input = document.querySelector('input');
var output = document.querySelector('#output');
input.addEventListener('keyup', function() {
send(this.value);
});
function send(val) {
clearTimeout(timer);
var d = Date.now() - lastsend;
if (d < 2000) {
timer = setTimeout(function() {
send(val);
}, d);
return;
}
if (val != lastsend) {
output.innerText = lastval = val;
lastsend = Date.now();
}
}
Зачем вам settimeout, если нужно определить определить разницу во времени между двумя событиями? new Date() не годится?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question