Considering your edit regarding this being focused on iPhone access...
The iPhone really just doesn't have that much power to it. You'll be better off just using onchange
or onblur
instead of onkeydown
.
An alternative to Dave's answer is waiting for the user to pause (e.g. for 5 seconds):
var textarea = document.getElementById('textarea');
function checkTextArea() {
if (textarea.value /* ... */) {
/* ... */
}
}
textarea.keyDownTimeout = null;
textarea.onkeydown = function () {
if (textarea.keyDownTimeout) clearTimeout(textarea.keyDownTimeout);
textarea.keyDownTimeout = setTimeout(checkTextArea, 5000);
};
This should set the timer with the first keydown, stopping and recreating the timer for each successive keydown. Finally calling 5 seconds after the user stops typing.
Also, note the lack of parenthesis after checkTextArea
. This will give setTimeout
the function's reference vs. its return
.
You can also set this up in a function to make it easier to use for multiple elements:
function setPauseTimer(element, timeout, callback) {
var timer = null;
element.onkeydown = function () {
if (timer) clearTimeout(timer);
timer = setTimeout(function(){ callback(element); }, timeout);
};
}
function checkTextArea(textarea) { /* moved from global to argument */
if (textarea.value /* ... */) {
/* ... */
}
}
setPauseTimer(document.getElementById('textarea'), 5000, checkTextArea);