0

I have the same problem as there: how to stop "setInterval"

but when i have a load inside the setInterval it doesnt work, this is what is inside test.php :

<div id="refresh">
<textarea></textarea>
</div>


<script src="jquery.js"></script>
<script>
$(function () {
  var timerId = 0;

  $('textarea').focus(function () {
    clearInterval(timerId);
  });

  $('textarea').blur(function () {
    timerId = setInterval(function () {
     $('#refresh').load('test.php #refresh');
    }, 1000);
  });
});
</script>
Community
  • 1
  • 1

1 Answers1

2

The problem is that your load call destroys and recreates the textarea, and nothing attaches the event handlers to the new textarea. The handlers you're attaching only get attached to the original one, not the new replacement.

You can solve that with event delegation, since jQuery makes sure blur and focus bubble (even though they don't bubble natively on all browsers);

$(function () {
  var timerId = 0;

  $('#refresh').on('focus', 'textarea', function () {
    clearInterval(timerId);
  });

  $('#refresh').on('blur', 'textarea', function () {
    timerId = setInterval(function () {
     $('#refresh').load('test.php #refresh');
    }, 1000);
  });
});

That hooks the events on the #refresh element, but fires the handlers only if the event originated in a descendant textarea of it.

Or since there's no reason to be looking up refresh repeatedly:

$(function () {
  var timerId = 0,
      refresh = $("#refresh");

  refresh.on('focus', 'textarea', function () {
    clearInterval(timerId);
  });

  refresh.on('blur', 'textarea', function () {
    timerId = setInterval(function () {
     refresh.load('test.php #refresh');
    }, 1000);
  });
});

Note that the change also means only textarea elements within the #refresh div get the events, whereas with your original code, all textarea elements on the page got it.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875