I'm calling an expensive function that dynamical changes as the end user types in a textbox. To reduce the amount of calls to the function I've used setTimeout
to delay calling the function, and if the function is called again whilst waiting to run, it'll also remove the last function request via clearTimeout
.
The function for this is:
// To not have different functions conflict
function makeDelay() {
var timerID = false;
return function (fn, timeout) {
if (timerID !== false) {
clearTimeout(timerID);
}
if (timeout == undefined) {
timeout = 500;
}
timerID = setTimeout(function() {
timerID = false;
fn();
}, timeout);
}
}
var delay = makeDelay();
var $peoplePicker = $('.ms-peoplePicker');
var $results = $peoplePicker.find(".ms-PeoplePicker-results");
However I don't know what the most idiomatic way to use this function is. I know that I can use one of the following:
A closure
function get(input, html_output) { return function () { if (!input) { return; } $.ajax('/_api/pp_search/' + input).done(function (data) { html_output[0].innerHTML = data; }) } } $peoplePicker.on('input', '.ms-PeoplePicker-searchField', function(event) { delay(get(event.currentTarget.value, $results)); });
bind
function get(input, html_output) { if (!input) { return; } $.ajax('/_api/pp_search/' + input).done(function (data) { html_output[0].innerHTML = data; }) } $peoplePicker.on('input', '.ms-PeoplePicker-searchField', function(event) { delay(get.bind(undefined, event.currentTarget.value, $results)); });
Anonymous functions
function get(input, html_output) { if (!input) { return; } $.ajax('/_api/pp_search/' + input).done(function (data) { html_output[0].innerHTML = data; }) } $peoplePicker.on('input', '.ms-PeoplePicker-searchField', function(event) { delay(function () { get(event.currentTarget.value, $results); }); });
Using a closure seems like the nicest, as you don't have to explicitly make a delayed function at usage via bind
or an anonymous function. However, anonymous functions seem to be the de facto way to call functions like these.
Which, if any, way should I use this function?
Notes
I ask because I made a JavaScript program that heavily used closures for this style of function, but was really hard to read.