Last active
September 1, 2023 13:14
-
-
Save ezirmusitua/1b14de3c4a3eb392f252476b77bf1a3b to your computer and use it in GitHub Desktop.
[Debounce window resize event] Debounce window resize event #javascript #frontend #perfermance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* -------------------------------------------- | |
* Detect device orientation | |
* and trigger changes based on it | |
--------------------------------------------*/ | |
function updateOrientation() { | |
// Detect whether device supports orientationchange event, otherwise fall back to the resize event | |
// Genius solution from http://stackoverflow.com/a/2307936 | |
let supportsOrientationChange = "onorientationchange"; | |
let orientationEvent = supportsOrientationChange ? "orientationchange" : "resize"; | |
let newAngle = null; | |
let newOrientation = null; | |
if(supportsOrientationChange){ | |
newAngle = window.orientation; | |
switch(newAngle){ | |
case 0: | |
case 180: | |
newOrientation = 'portrait'; | |
break; | |
case 90: | |
case -90: | |
newOrientation = 'landscape'; | |
break; | |
} | |
} else { | |
if(document.width < document.height){ | |
newOrientation = 'portrait' | |
} else { | |
newOrientation = 'landscape' | |
} | |
} | |
// Do the processing here | |
/* | |
* Beautiful debouncing for resize event firing too much on the PC | |
* by Pim Jager http://stackoverflow.com/a/668185/930987 | |
*/ | |
resizeEvent = false; | |
window.addEventListener(orientationEvent, function() { | |
if(!resizeEvent) { | |
clearTimeout(resizeEvent); | |
resizeEvent = setTimeout(updateOrientation, 500) // half a second should be enough for a modern PC | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment