javascript - Only do an action if content has not changed in 500ms -
currently have
$('document').ready(function(){ $('input').keyup(function(){ $('#output').text($(this).text()); }); });
what want is,
when keypress registered wait 500ms, if key pressed again within 500ms, wait 500ms keypress.
once 500ms has gone by, run $('#output').text($(this).text());
how go managing timeout?
you can set , clear timer, this:
$(function(){ $('input').keyup(function(){ cleartimeout($.data(this, 'timer')); var input = this; $.data(this, 'timer', settimeout(function() { $('#output').text($(input).text()); }, 500)); }); });
what on keyup
sets 500ms delay before running $('#output').text($(input).text())
, if key pressed before happens, cancels timer , starts another...so won't run until 500ms of idle. using $.data()
store timer on specific element, generic solution work number of elements on page.
as aside, $('document').ready()
should $(document).ready()
or shorter $(function() {
have above, "document"
(in quotes) runs selector unnecessarily.
Comments
Post a Comment