Friday, February 13, 2015

JavaScript: Function for adding slight delay to a rest request

A piece of functionality was added in the codebase I work on. It basically dynamically searches as you type stuff in. This is pretty common stuff and you see it in google search. The thing is that you don't necessarily want to search at every key press. For example, if someone is rapidly typing you only want to search after they finish rapidly typing. So the following code was added. Note that this is using Angular and TypeScript, but nothing in it requires Angular or TypeScript.

public search(delay: number = 300) {
    this.$timeout.cancel(this.timer);
    this.timer = this.$timeout(() => {
        var searchTerm = this.$scope.searchTerm.name || '*';
        this.filter.searchBy('name', searchTerm);
        this.filter.goToPage(0);
        this.retentionService.list(this.filter).then( (data) => {
            this.$scope.retentions = data;
        }).finally(() => {
            this.$scope.loadInProgress=false;
        });
    }, delay);
}

To me this is two pieces of functionality. One to do search. The other to do something after a delay and to reset the delay every time the function is called. Separating these two pieces of functionality out is kind of a simple exercise in functional programming and also demonstrates the expressive power of functional programming. Here is what I did:

var search = runAfterThisNotCalled(delay, () => {
    this.$scope.searchTerm.name || '*';
    this.filter.searchBy('name', searchTerm);
    this.filter.goToPage(0);
    this.retentionService.list(this.filter).then( (data) => {
this.$scope.retentions = data;
    }).finally(() => {
        this.$scope.loadInProgress=false;
    });
})

// goes in AsynchrnousUtilities
function runAfterThisNotCalled(delay, func) {
var myTimer;
return () => {
this.$timeout.cancel(myTimer);
myTimer = this.$timeout(func,delay)
}


I have made a jsfiddle to demonstrate: http://jsfiddle.net/willseitz/3erm0fe0/. Note that in this example you need to hit the button once to start the behavior.

Anyway, this is a simple example of the kind of power and expressivity that functional programming gives you.


No comments:

Post a Comment