0

var init = true;

$('#btn').on('click', delay(function() {

  $('#text').append('click');
  init = false;

}, 100));

function delay(fn, ms, enabled = true) {

  $('#text').append(init);

  // if(init) disable delay

  let timer = 0;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(fn.bind(this, ...args), ms || 0);

  }

}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

<button id='btn'> TRIGGER </button>
<div id="text"></div>

Init is a global variable which is meant to be used inside delay function to disable delay (init true/false) only on event listener initialisation.

The problem is that the delay function is triggered only once and ignores the change (to false) of the init variable.

For example, try clicking the trigger button. The init variable value is printed only for the first time.

Mara Black
  • 1,666
  • 18
  • 23
mr.work
  • 173
  • 10
  • Does this answer your question? [Calling vs invoking a function](https://stackoverflow.com/questions/50884893/calling-vs-invoking-a-function) – Mitya Dec 16 '19 at 11:27

3 Answers3

0

You are calling the delay function in a wrong way in the click handler. You have to call it like so:

$('#btn').on('click', function () {

    delay(function() {

        $('#text').append('click');
        init = false;

    }, 100);
});
John Archer
  • 2,407
  • 2
  • 25
  • 33
0

You will have to check for the value of init inside the function, like this:

$('#btn').on('click', delay(function() {

if(init) {
  $('#text').append('click');
  init = false;
  }

}, 100));
Mr. X
  • 706
  • 12
  • 23
0

At the moment I don't know why append is not working but with a little workaround you can obtain what you want. Concatenate the original text and the actual one and use text() to set it again:

var init = true;

$('#btn').on('click', function() {
  $('#text').text(init);
  setTimeout(myDelay, 5000);
});

function myDelay() {

  let originalText = $('#text').text();
  init = false;

  console.log("init is false");
  console.log("original text displayed: " + originalText);
  
  $('#text').text(originalText + " " + init);

}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

<button id='btn'> TRIGGER </button>
<div id="text"></div>
Mara Black
  • 1,666
  • 18
  • 23