Window.onresize triggered multiple times
- 2020-03-26 23:46:14
- OfStack
I used window.onresize to ensure that the page would display normally when the window size was changed, so I used window.onresize. However, I found that the state of the page was always wrong after each onresize.
//
As for the number of times the onresize event has been triggered, it varies from browser to browser, safari, opera and firefox all have the same number (only one version test is used respectively, which is relatively new).
//ie6 triggers 2 times in quirk and 3 times in standard; Ie7, 8 are both twice in quirk and standard.
window.onresize = function(){
console.log( 'hello world');
}
onresize It doesn't matter how many times it's triggered, it's the solution: call it once for multiple triggers onresize On the function
//
//Debounce is a word I do not know how to translate, brother. :)
//
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
//I didn't write the code.
//Code description:
debounce accept 3 Two parameters, the last two optional; The first one is to debounce The function, Second representative debouce The third executes the function at the beginning or the end of the period ;
debounce Returns a wrapped function with at least one interval between executions threshold And less than threshold The interval's call restarts the timer ( The interval between the two calls );
the clearTimeout( timeout ) Change for timer = null; The interval between two executions of the return function is at least one threshold And less than threshold The interval's call restarts the timer ( The interval between the two calls );
//Resolve multiple calls to onresize
[code]
window.onresize = debounce( function(){
alert( 'hello world');
}, 100, true)
// It is also used in auto-completion to reduce the number of requests to the server debounce, It is sent only if the continuous keystroke interval is greater than a certain value ajax
Resize can only be bound to one?
Yes, in this way, only one resize can be bound to a page.
The code below will always print a "2" without a "1".
//Resize can only bind and execute one. At this point, only the latter one is executed.
window.onresize = function(){
console.log("1")
}
window.onresize = function(){
console.log("2")
}
But if I write it this way, I can do both.
//The addEventListener binding can be executed twice
window.addEventListener("resize", function(){
console.log("3")
});
window.addEventListener("resize", function(){
console.log("4")
});
And that's it