0

I am using Turbolinks.visit action, via $(document).on("input");...

Html

<form id="mainSearch" method="get" autocomplete="off">
    <input type="search" name="s" placeholder="Search" />
</form>

Javascript

$(document).off().on("input", "#mainSearch", function(e) {

        e.stopImmediatePropagation();
        e.stopPropagation();
        e.preventDefault();

        var ser     = $(this).serialize();

        setTimeout(function(){
            Turbolinks.visit(
                homeurl+"/?"+ser,
                {
                    change: ['content']
                }
            );
        },110);

        return false;
    });  

It is working right but event fired multiple request when hold down a key.

enter image description here

do how I take precautions to keep it pressed? .on("input"

2 Answers2

0

Did you forget to cancel the previous timer?

var timer = null;

$(document).off().on("input", "#mainSearch", function(e) {

    e.stopImmediatePropagation();
    e.stopPropagation();
    e.preventDefault();

    var ser= $(this).serialize();

    clearInterval(timer);

    timer = setTimeout(function(){
        Turbolinks.visit(
            homeurl+"/?"+ser,
            {
                change: ['content']
            }
        );
    },110);

    return false;
});  

Edit: Instead of re-inventing the wheel it's always a good choice to use existing solutions, $.debounce() is what you are looking for.

Rahul Gandhi
  • 1,035
  • 1
  • 11
  • 24
  • What should be the best time setting for a normal write speed? I'll try it "500 ms" and good work but Is there an appropriate value for user experience? –  Oct 23 '18 at 17:10
  • 1
    @l6ls I would recommend using "$.debounce" . 500ms is a good starting point. Also, please have a look into this: https://stackoverflow.com/a/44755058/2860486 – Rahul Gandhi Oct 24 '18 at 10:53
  • thx, need to know the basics before. but I'll try it now. " jquery.ba-throttle-debounce.min.js " It is right script? http://github.com/cowboy/jquery-throttle-debounce/raw/v1.1/jquery.ba-throttle-debounce.min.js –  Oct 24 '18 at 11:46
  • @l6ls Yah, that's one of the popular plugins. If you don't want to add a plugin, (as it includes throttle as well which you might not be using as of now) you can simply take the code from here: https://davidwalsh.name/function-debounce – Rahul Gandhi Oct 24 '18 at 12:39
0

You might be looking for https://stackoverflow.com/a/27787793/5523033 since you're using JQuery you can use $.debounce

and here's a few examples to play around with http://jsfiddle.net/cowboy/cTZJU/

Andrei
  • 1,196
  • 1
  • 11
  • 25