Search code examples
javascriptjqueryimagedelayloader

set jquery loader when timeout (window.setTimeout)


I now have the following functionality in my jQuery file:

var timer;
var delay = 1500; // 1,5 second delay after last input

$("#qr_data").bind("input", function (e) {
    window.clearTimeout(timer);
    timer = window.setTimeout(function(){
        // get qr code data
        var qr_data = $('#qr_data').val();

        var data = getVCardData(qr_data);

        $("#helpqrcode").modal("hide");


    }, delay);
});

As you can see I have a delay of 1,5 second. Is it possible that I can show an image loader while the 1,5 second? In my HTML I have an image like this:

<img id="loading" style="display:none; width:200px;" alt="loader" src="recourses/imgs/loader.gif" />

Solution

  • Changed the image to text, for convenience for demo.

    var timer;
    var delay = 1500; // 1.5 second delay after last input
    
    $("#qr_data").bind("input", function (e) {
        window.clearTimeout(timer);
      
        // When user stop input, show the image here.
        $("#test").show();
      
        
        timer = window.setTimeout(function(){
            // When the time is 1.5 second after last input, hide the image.
            $("#test").hide();
          
            // get qr code data
            var qr_data = $('#qr_data').val();
            console.log(qr_data);
            
            
        }, delay);
    });
    #test {
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <input type="text" id="qr_data" />
    <div id="test">Typing</div>