简体   繁体   中英

How to stop window.onresize event when scroll ? I only need to fire once?

I tried all the way, but window.onresize still fire when swiping up or down on the page.

First, I try a basic command line:

window.onresize = function (event) {
  setTimeout(Orientation,500);
}

function Orientation() {
 if (window.innerHeight > window.innerWidth) {
   alert("Portrait");
  }
else {
   alert("Landscape");
  }
}

When alert show up, i click OK. But when i swiping up or down on the page, alert show up again, alway like that...

I will try jquery's David Walsh:

function debounce(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);
    };
};

var myEfficientFn = debounce(function() {
    if (window.innerHeight > window.innerWidth) {
   alert("Portrait");
  }
else {
   alert("Landscape");
  }
}, 250);

window.addEventListener('resize', myEfficientFn);

The result is the same!

You can try here by Mobile or Tablet: http://hangaumy.com/test.html

Is there any other way for this event ? Many thanks !

Put a condition in your function so your function only fires when you want it to.

 window.onresize = doSomething; var count=0 function doSomething(x) { if(count<1){ alert('Go' + x); } count+=1; } 

I can't find a way to use event resize in this case but I found another solution:

var orien = '';
setInterval(function() {
  if (window.innerHeight >= window.innerWidth && orien != 'Portrait') {
    alert('Portrait');
    orien = 'Portrait';
    return;
  }
  if (window.innerHeight < window.innerWidth && orien != 'Landscape') {
    alert('Landscape');
    orien = 'Landscape';
  }
}, 500);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM