javascript - clearTimeout & setTimeout not working -
as follow of question, i'd know why not working
$("#textarea").keydown(function(){ oldvalue = $("#textarea").val(); }); $("#textarea").keyup(function(){ var starttimer = null; if(starttimer) cleartimeout(starttimer); starttimer = settimeout(function(){ var newvalue = $("#textarea").val(); // out of comparison alert(something) // alert comparison oldvalue = newvalue; },2000);
the required behavior alert message when user hasn't typed 2 seconds. works comparison part, however, doesn't stop alert message when keep typing should. instead, same number of alerts number of keys pressed. tried version of creating , deleting cookies, worked fine. wrong in particular case?
you're getting new starttimer
(and initializing null
) on each call keyup
handler. try declaring in outside scope:
(function() { var starttimer = null; var oldvalue; // declare too, isn't global $("#textarea").keydown(function(){ oldvalue = $("#textarea").val(); }); $("#textarea").keyup(function(){ if(starttimer) { cleartimeout(starttimer); } starttimer = settimeout(function(){ var newvalue = $("#textarea").val(); // out of comparison alert(something) // alert comparison oldvalue = newvalue; },2000); }); })();
Comments
Post a Comment