[Fixed]-Cancel ajax calls?

1๐Ÿ‘

โœ…

If they are DB queries that are taking up time, then basically nothing will stop them besides stopping the database server, which is of course not tangible. If it is computation in nested loops for example, then you could use cache to detect whether another request has been submitted from the same user. Basically:

from django.core.cache import cache    

def view(request):
    start_time = timestamp # timezone.now() etc.
    cache.set(request.session.session_key + 'some_identifier', start_time)
    for q in werty:
        # Very expensive computation with millions of loops
        if start_time != cache.get(request.session.session_key + 'some_identifier'):
            break
        else:
            # Continue the nasty computations
    else:
        cache.delete(request.session.session_key + 'some_identifier')

But the Django part aside โ€“ what I would do: in JS add a condition that when the search word is less than 3 chars, then it waits 0.5s (or less, whatever you like) before searching. And if another char is added then search right away.
I.e.

var timeout;

function srch(param) {
    timeout = false;
    if (param.length < 3) {
        timeout = true;
        setTimeout(function () {
            if (timeout) {
                $.ajax({blah: blah});
            }
        }, 500);
    } else {
        $.ajax({blah: blah});
    }
}
๐Ÿ‘คwanaryytel

Leave a comment