I was working on an annoying bug lately that only and specifically occurs on Iphone5.
I have a Javascript function that needs to execute when the orientation changes on mobile devices.
Thus this function needs to fire when the device’s orientation changes from landscape to
portrait or vice versa. Here’s my window.resize
event in jQuery listening for the resize event. The expected behavior is after the resize/orientation change event occurs, execute the declared function inside the listener.
$(window).on('orientationchange resize', () => {
//call my declared function here
});
However, I noticed that Iphone5 executes the function too early or even before the screen orientation changes. Another thing that gets into my nerves is there are times that my function executes correctly making the bug harder to catch due to inconsistency.
As you see, the issue here is inconsistency when resize event occurs on Iphone5. To fix, I have to use a debounce concept in Javascript.
let resizeTimer, delay = 320, pos = 0;
$(window).on('orientationchange resize', () => {
clearTimeout(resizeTimer);
//ensures that we execute the function after the change event is called/fired
resizeTimer = setTimeout(() => {
//call my declared function here
}, delay);
});
By setting a 320 ms delay, I can ensure that my declared function is called after the resize event happened.