在去抖功能中设置全局变量

时间:2019-02-14 11:44:48

标签: javascript

如何更改内部的称为反跳功能的全局变量。这是什么意思-Can someone explain the "debounce" function in Javascript

function debounce(func, wait) {
  var timeout;
  return function () {
    var content = this, args = arguments;
    var later = function() {
      timeout = null;
      func.apply(content, args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

var MANIPULATEDWPAGE = false;
function manipulatedwpage() {
  if (!MANIPULATEDWPAGE) {

     //MY CODE
     MANIPULATEDWPAGE = true; //only ones during debounce process

  }
}
window.addEventListener('resize', manipulatedwpage());
window.addEventListener('scroll', manipulatedwpage());

function calldeb() {

    //code after debounce done
    MANIPULATEDWPAGE = false;
    // <--- PROBLEM --- MANIPULATEDWPAGE is not changed

}
var debvar = debounce(calldeb, 2000);
window.addEventListener('resize', debvar);
window.addEventListener('scroll', debvar); 

1 个答案:

答案 0 :(得分:0)

这是您的代码正在运行的操作,简化为没有控制流语句的操作:

var MANIPULATEDWPAGE = false; // initial declaration
MANIPULATEDWPAGE = true; // run from function manipulatedwpage()
MANIPULATEDWPAGE = false; // run from debvar

您在resizescroll事件上都有两个处理程序。其中一个将您的global设置为true,然后另一个将您的global设置为true,然后立即将其重新设置为false,从而使它看起来像从原始状态没有改变一样。