Hello. I'm trying to create a javascript barcode API, that reads from my USB barcode reader and calls an action upon completion. The reading itself is not complicated at all, since the barcode reader functions exactly as typing the same numbers on my keyboard. So scanning a barcode with;


would be the same as typing it on my keyboard, but of course much faster. The problem lies in my "API" which dosn't always respond to the barcode length correctly, hence executing the actions at the wrong time (see code below).

A scenario in my application would be to separate multiple barcodes with a semicolon, which is what I'm trying to do with the code below. Copy paste the following code, and run it in your browser:

OBS! Only tested i Opera (since I'm developing for a closed enviroment)
HTML Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Barcode reader</title>
<script type="text/javascript">

document.onkeydown = keyhandler;

currentstring = '';
barcodelength = 7;

function keyhandler(e){
	if (document.layers){ Key = e.which; }
    else{Key = window.event.keyCode;}
	// Initialize timer on empty string
	if(currentstring == ''){
		timer = setTimeout("cancel()",5000);
	// Add key to currentstring
	currentstring += String.fromCharCode(Key);
	// Run actions if currentstring matches barcodelength
	if(currentstring.length == barcodelength){
		document.getElementById('barcode').value += ';';
		currentstring = '';
} // if keyhandler
function cancel(){
	currentstring = '';

<input id="barcode" name="barcode" type="text" value="" size="50" />
1. Click on the input field
2. Type 50505050505050505050505050... on your keyboard at a rate that types in at least 7 numbers/5seconds, to emulate the barcode reader. (the timeout is usually 300ms insted of 5 seconds when having the acutal barcode reader attached)

In a perfect world, this would be manipulated to (notice that all barcodes has a length of 7 numbers):

But it dosn't, I'm sure it's looking more like this: (where some barcodes where separated to early or to late. Some are of 6 numbers in length, some 7, which is the correct, and some are even 8!):

Try to type the numbers very fast and slow (but within 5 seconds).

Why doesn't my code always separate my barcodes evenly?

(note: I know you can program a barcode reader so it sends a certain keystroke, eg. ; after each scan, but that's not an option since I'm calling different functions in my application)