1

This question's answers propose using window.setInterval as the only reliable way to immediately detect (without waiting for blur) if a text box's content is changed, given that some textbox changes can happen via events other than key presses.

Even on my desktop PC I see IE or Firefox chewing up a non-trivial percentage of CPU with a 500 msec setInterval running with a relatively simple handler checking a few textboxes. This is OK on a desktop PC but on laptops and mobiles it will hurt battery life.

What's a good way using jquery to minimize CPU utilization but still provide fast updates in response to changes (including clipboard pasting, ajax updates, etc. not just key presses) to a textbox?

Community
  • 1
  • 1
Justin Grant
  • 44,807
  • 15
  • 124
  • 208

2 Answers2

4

onBlur is when you have moved away from an object without necessarily changing it.

onChange is only called after you have moved away from an object that you have changed the value of.

One of these should fit your needs. If not, the various keypress events will trigger for each character change.

If these don't then regularly updating a single javascript variable could not possibly take as much processing power as you are saying UNLESS your selector is causing some odd DOM behavior.

Try this: Reference the element by id, and store that reference in a js variable. Updating and changing another variable via this reference is then a trivial operation.

cdeszaq
  • 30,869
  • 25
  • 117
  • 173
mvrak
  • 501
  • 3
  • 12
  • 1
    I implemented your suggestions, and discovered the main CPU problem: a comparison bug that resulted in setting text() of an element repeatedly. Even if the text was the same as the old text, it was taking 50% of one CPU core to update it. IE9 is down to <1% now. But Firefox is still taking 2%-3% just to read from the DOM using the simplest possible selectors (and caching them in js variables too). I need to bring it down further meaning I need @andi's suggestion too. I'm upvoting both of your answers. Wish I could accept both of them too! – Justin Grant Jan 24 '12 at 17:22
2

Start running your window.setInterval (or setTimeout) checker on focus of that text box, and kill it on blur. That way you won't be using up CPU power when the cursor isn't in the text box.

andi
  • 6,442
  • 1
  • 18
  • 43
  • While that would work, I can't conceive why this operation would take any measurable amount of time unless there is a bad selector, so I am not recommending it. – mvrak Jan 23 '12 at 18:41
  • 1
    I agree, this operation isn't so bad in the first place. I'm just answering this guy's question... a miniscule improvement to a miniscule problem. =) – andi Jan 24 '12 at 16:27