Home > Article > Web Front-end > Methods to prevent high-frequency triggering and high-frequency calls of event functions in JavaScript_javascript skills
The most basic function of JavaScript in web pages is to monitor or respond to user actions, which is very useful. Some of the user's actions are very frequent, and some are very rare. Some listener functions execute lightning fast, while others are heavy-handed and can drag the browser to death. Take the resize event of the browser window as an example. This event will be triggered once for every scale change in the size of the browser window. If the listener is large, your browser will soon be overwhelmed.
Obviously, we cannot allow the browser to be brought down, but we cannot delete the delete listener. However, we can limit the frequency of function calls and weaken the impact of event function execution. Instead of triggering the listener function once for each size change of the window, we can now set the minimum interval for triggering the listener function to be greater than a certain number of milliseconds, so that it maintains a reasonable calling channel and ensures that the user experience is not destroyed. There is a good js tool library called Underscore.js, which has a simple method that allows you to easily create listeners that reduce the frequency of event function triggers.
JavaScript code
The code of the frequency reduction listener is very simple:
// Does all the layout updating here
}, 500); // Run every 500 milliseconds at least
// Add the event listener
window.addEventListener("resize", updateLayout, false);
...The bottom layer of this Underscore.js code actually uses interval to check the frequency of event function calls:
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
If (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
// Use it!
window.addEvent("resize", myFn.debounce(500));