Skip to content

Instantly share code, notes, and snippets.

@ezirmusitua
Last active September 1, 2023 13:14
Show Gist options
  • Save ezirmusitua/1b14de3c4a3eb392f252476b77bf1a3b to your computer and use it in GitHub Desktop.
Save ezirmusitua/1b14de3c4a3eb392f252476b77bf1a3b to your computer and use it in GitHub Desktop.
[Debounce window resize event] Debounce window resize event #javascript #frontend #perfermance
/* --------------------------------------------
* 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