Javascript advanced tips sharing

  • 2020-03-30 02:06:01
  • OfStack

After finishing up the Ajax section last time, and finishing up the advanced tips section this week, let's do the same.

When you try to stretch the browser, the console instantly displays more than 100 I's.
Change the way you write it, for example:

var i = 0, j = 1;
window.onresize = function(){
     if(j % 2 == 0){

Create a variable j that is executed only if the j is even, which is half the number of executions.
When handled like this, you can reduce the number of executions by 50%, but you won't feel the difference to the user.

There is also a function throttling using timer.
The core code is as follows:

function throttle(method , context){
   method.tId = setTimeout(function(){;

This passes in the execution function and the execution environment of the function (that is, the object to which the this in the execution function points), and then the queue of actions is cleared before the action is executed.
This form allows for better control over the frequency of movement.
If it's a browser stretch, then as long as you stretch fast enough and the time interval between each trigger is within 100ms, only the last result will be executed.

8. Custom events
The essence is the observer pattern. The basic pattern is three functions,
A function is the binding event, a function is the triggering event, and a function is the removal of the binding.
This pattern can significantly reduce code coupling.

Related articles: