How to prevent JS jitter through examples

Time:2019-10-28

Preface

This topic often exists at the same time with event triggers. In order to investigate whether the interviewers can comprehensively consider the implementation ideas in some specific business processes (information flow, search box input query), etc.

subject

In some information lists, waterfall flow is usually used to load the corresponding data when rolling one screen. Please think about how to avoid problems arising from continuous pull-down.

In general, if you encounter such an interview question, anti jitter mechanism, it can be solved very well. Twitter is the earliest application practice in this field. The developer wrote a blog and elaborated on how to solve this problem in detail. Then, when it comes to anti jitter, its core connotation lies in delay processing, that is to say, delay a series of event handlers to ensure the first event processing pushed in.


event.on('scroll', function(e){ 
var fun; 
return function(){ 
if(fun) clearTimeout(fun);
fun = setTimeout(function(){ 
// console.log('1')
},500);
}
}());

This is the most common way. If there are many scrolls, you can put the real function in the timer first.

Let’s abstract it as follows:


function de(something,delay){ 
var fun; 
return function(){ 
if(fun) clearTimeout(fun);
fun = setTimeout(function(){ 
something();
},delay);
}
}
function scrollToList(){
}
event.on('scroll', de(scrollToList,1000))
event.on('scroll', de(scrollToList,2000))

Obviously, this is a weak explosion. Is there a better way? Yes, like throttling.

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.