Search code examples
jqueryhtmldelaytimingbenchmarking

How to delay jquery prop(,) with no extra function


I have some radio buttons that i want to change which one is checked with jQuery all the time half a second after an image is faded, without adding any extra function, this is my code:

$("#myImage").fadeOut(1000);
$("#myRadioInput").delay(500).prop("checked",true)

Why doesn't it work as i want?


Solution

  • The animation is non blocking. Those functions will practically be called at the same time. You can see your example here:

    $("#doIt").on('click', function(e) {
      e.preventDefault();
    
      $("#myDiv").fadeOut(1000);
      $("#myRadioInput").delay(500).prop("checked", true);
    
    })
    #myDiv {
      height: 10px;
      width: 10px;
      background: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <button type="button" id="doIt">Do It!</button>
    
    <div id="myDiv"></div>
    <input id="myRadioInput" type="checkbox">

    Also, delay does not function as you expect. It does not "pause" the chain. It adds a delay to a queue, normally fx, which would allow you to pause further animations, but not pause the next call in your chain. You can see examples of this in the docs.

    In the question, you say:

    without adding any extra function

    I don't understand the motivation behind this requirement. The obvious solution is to use "extra" functions. We are programming after all ;)

    $("#doIt").on('click', function(e) {
      e.preventDefault();
    
      $("#myDiv").fadeOut(1000, function() {
        setTimeout(function() {
          $("#myRadioInput").delay(500).prop("checked", true);
        }, 500);
      });
    
    })
    #myDiv {
      height: 10px;
      width: 10px;
      background: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <button type="button" id="doIt">Do It!</button>
    
    <div id="myDiv"></div>
    <input id="myRadioInput" type="checkbox">