0

How to change the global variable inside called debounce function. What does it mean - 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); 
alexso
  • 163
  • 1
  • 8
  • 2
    There's no global variable in the debounce function. – Barmar Feb 14 '19 at 11:48
  • 2
    The second argument to `addEventListener` shouldn't have `()` after it. You want to pass a function reference so that the function will be called when the event happpens, not call the function immediately. – Barmar Feb 14 '19 at 11:51
  • MANIPULATEDWPAGE means global variable because is outside function – alexso Feb 14 '19 at 11:52
  • I thought you were asking about a global variable that's actually in the `debounce()` function, not a variable that's used by the function that's being debounced. – Barmar Feb 14 '19 at 11:53
  • I don't know how change "global" variable MANIPULATEDWPAGE in function calldeb() – alexso Feb 14 '19 at 12:06
  • You're doing it correctly already. Just assign the variable, there's nothing more to it. If you can't see the change, something else must be changing it back to `true`. – Barmar Feb 14 '19 at 12:13
  • Solved, mistake was in listener, yes problem with addEventListener and (), thanks for help. – alexso Feb 14 '19 at 12:40

1 Answers1

0

Here's the operations your code is running, reduced to just operations without control flow statements:

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

You have two handlers on both the resize and scroll events. One of them sets your global to true, and then the other one comes along and immediately sets it back to false, making it look like it hasn't changed from its original state.

Effective Robot
  • 366
  • 1
  • 6
  • OK, just manipwpage() without () in resize and scroll listener, solved, unnecessary mistake elsewhere, sorry and thanks for help. – alexso Feb 14 '19 at 12:17