简体   繁体   English

setTimeOut 如何与调整大小事件侦听器一起使用?

[英]How does setTimeOut work with resize event listener?

From the Mozilla site on resize , I don't understand the below example of how resizeTimeout is made to null inside the setTimeout function.从关于resize的 Mozilla站点,我不明白下面的示例如何在setTimeout函数resizeTimeout设为null What purpose does that serve?这样做的目的是什么? By declaring both var resizeTimeout;通过声明var resizeTimeout; and then setting it to null , the conditional of (!resizeTimeout) will be true, so what difference does it make to set it to null ?然后将其设置为null(!resizeTimeout)的条件将为真,那么将其设置为null什么区别?

(function() {

  window.addEventListener("resize", resizeThrottler, false);

  var resizeTimeout;
  function resizeThrottler() {
    // ignore resize events as long as an actualResizeHandler execution is in the queue
    if ( !resizeTimeout ) {
      resizeTimeout = setTimeout(function() {
        resizeTimeout = null;
        actualResizeHandler();

       // The actualResizeHandler will execute at a rate of 15fps
       }, 66);
    }
  }

  function actualResizeHandler() {
    // handle the resize event
    ...
  }

}());

This is a common technique called "throttling," as the function name suggests.顾名思义,这是一种称为“节流”的常用技术。 This makes it so the resize handler will only be called at most every 66 milliseconds.这使得调整大小处理程序最多只能每 66 毫秒调用一次。

If the user is resizing the window, it will keep firing that event and triggering the resizeThrottler function constantly.如果用户正在调整窗口大小,它将继续触发该事件并不断触发 resizeThrottler 函数。 However, if you executed the actualResizeHandler every time the resize event was triggered, your page would get bogged down.但是,如果每次触发 resize 事件时都执行 actualResizeHandler,您的页面就会陷入困境。

Since the resizeTimeout is being set to null WITHIN the timeout function, the expression !resizeTimeout will only be true at most every 66 milliseconds.由于在超时函数内将 resizeTimeout 设置为 null,表达式!resizeTimeout最多每 66 毫秒才为 true。 Once those 66 milliseconds are up, you can set another one.一旦这 66 毫秒到了,您就可以设置另一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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