I'm trying to debounce keystrokes in a form input on IE Mobile 6 (from what I gather, about on par with IE 3-4 in terms of support).
Due to the lack of support, I can't add event listeners after declaration (i.e., document.getElementById('elementId').addEventListener(...)
doesn't work), I can only do them inline, like onkeydown="doSomething()"
.
Here is a jsBin.
So, with this debounce function (taken from David Walsh):
function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
The recommended way to set up your event function would be like:
var doSomething = debounce(function() { ... }, 250);
However, I can't use this doSomething
style function in the inline event listeners on IE Mobile 6.
So, in the markup, I've tried:
<input type="text" onkeydown="doSomething()" />
And
<input type="text" onkeydown="doSomething()()" />
And in javascript:
// return the result of debounce()
function doSomething() {
return debounce(function() { ... }, 250);
}
// just debounce()
function doSomething() {
debounce(function() { ... }, 250);
}
// return the result of the returned function of debounce, aka debounce()()
function doSomething() {
return debounce(function() { ... }, 250)();
}
I've also just tried putting the whole contents of the debounce function inside of this function, like:
function doSomething() {
var timeout, func, wait, immediate;
func = function() {
console.log('test');
};
wait = 250;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
So, long question short:
How can I write this exact statement:
var doSomething = debounce(...);
Like this:
function doSomething() {
}