Reputation: 47111
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?
Upvotes: 2
Views: 2668
Reputation: 11
I think you should use threads for this. Create thread for keys and in each thread you can calculate time between key strokes. For more explanation you watch my video for this exact solution.
https://www.youtube.com/watch?v=sDGYM8LeZh8
See the code below:
import keyboard # keyboard library
import string # string for capturing keyboard key codes
import time # for capturing time
from threading import * # threads for keypresses
# get the keys
keys = list(string.ascii_lowercase)
# key listener
def listen(key):
while True:
global timeda # global variable for storing time for 1st keypress
global newda # global variable for storing time for next keypress
keyboard.wait(key) # when key is presses
# check if variables are defined
try:
timeda
newda
# this will run for the first keypress only so assign initial time to variable
except NameError:
timeda = time.time()
newda = time.time()
print("First key is pressed at "+str(round(newda,2)))
print('\n==========\n')
# for all keypresses except for the first will record time here
else:
newda = time.time() # assign time for next keypressed
newtime = newda - timeda # get difference between two keys presses
# just to test time of first keypress
print("Previous keypress was at "+str(round(timeda,2)))
# just to test time of next keypress
print("Current keypress is at "+ str(round(newda,2)))
# convert time into seconds
newtime = newtime % 60
print("Difference between two keypresses is "+str(round(newtime,2)))
print('\n==========\n') # need some space for printing difference
timeda = time.time()
# creating threads for keys and assigning event and args
threads = [Thread(target=listen, kwargs={'key':key}) for key in keys]
# calling each thread
for thread in threads:
thread.start()
# thats it
Upvotes: 0
Reputation: 79810
Not sure how computationally intensive this is, if it is easy to reset timeout on timer.
Upvotes: 0
Reputation: 1782
Something like this:
NSDate *start = [NSDate date];
// do the thing you are timing
NSDate *stop = [NSDate date];
NSTimeInterval duration = [start timeIntervalSinceDate:stop];
Upvotes: 8
Reputation: 15003
Probably a better approach is to pick up the NSEvent associated with each keypress and compare the difference in their -timestamp property.
Upvotes: 5
Reputation: 96333
Get the current time, then subtract the previous current time. See -[NSDate timeIntervalSinceDate:].
Upvotes: 2