0

I am trying to set timeout for my ajaxGet function as shown here.

Without the code that I have found I have:

$('#search').on('keyup', function() {
    var query;
    query = $(this).val();
    ajaxGet('{% url "distributors:search_dist" %}', {
        'query': query
    }, function(content) {
        $('#distributors').html(content);
        // alert(content);
        set_favorite();
    })
});

And it works nice.

After I implemented solution for delay I have:

var delay = (function() {
    var timer = 0;
    return function(callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
})();
$('#search').keyup(function() {
    delay(function() {
        var query;
        query = $(this).val();
        ajaxGet('{% url "distributors:search_dist" %}', {
            'query': query
        }, function(content) {
            // $('#distributors').html(content);
            alert(content);
            set_favorite();
        })
    }, 1000);
});

But this doesn't work. I believe that the problem is is JS because it even doesn't run ajaxGet()...

Any ideas what I am doing wrong?

Community
  • 1
  • 1
pythad
  • 4,241
  • 2
  • 19
  • 41

2 Answers2

0

You could create a setTimeout within the event like :

$('#search').keyup(function() {
    window.setTimeout(function(){
var query;
        query = $(this).val();
        ajaxGet('{% url "distributors:search_dist" %}', {
            'query': query
        }, function(content) {
            // $('#distributors').html(content);
            alert(content);
            set_favorite();
        })
},1000);
});
Rosmarine Popcorn
  • 10,761
  • 11
  • 59
  • 89
0

I am not very familiar with JS but I've found my problem:

I had to replace query = $(this).val(); with query = $('#search').val();

pythad
  • 4,241
  • 2
  • 19
  • 41