tags:

views:

852

answers:

4

I'm trying to write an app where I need to accept keypresses, and call a function whenever the user has stopped typing (or when there is a specified delay between keystrokes).

How do I measure the time between two keystrokes?

+1  A: 

Get the current time, then subtract the previous current time. See -[NSDate timeIntervalSinceDate:].

Peter Hosey
+3  A: 

Probably a better approach is to pick up the NSEvent associated with each keypress and compare the difference in their -timestamp property.

Mike Abdullah
+2  A: 

Something like this:

NSDate *start = [NSDate date];
// do the thing you are timing
NSDate *stop = [NSDate date];

NSTimeInterval duration = [start timeIntervalSinceDate:stop];
David Weiss
I think the last line should be: NSTimeInterval duration = [stop timeIntervalSinceDate:start];
splattne
A: 
  • You could setup timer to execute something X amount of time after user stopped typing, then restart the time each time user type something - so it will delay timer expiry.

Not sure how computationally intensive this is, if it is easy to reset timeout on timer.

  • Optionally you could start timer on last keystroke for X amount of time. On expiry you could check timestamp of last keystroke, which you saved on last keystroke, then you can either restart timer starting with (timeout - last keystroke time) amount of time. On expiry do the check again. Then, on each keystroke if timer is running only update timestamp of last keystroke ...
stefanB