There are two input fields, one user enters data, the second varies depending on what the user has entered. How to set a delay of 1 second after which the second input starts to change?

  • one
    via setTimeout(function(){ myFunction(param); }, 1000); - Den

3 answers 3

 ~function () { var t; $('#text-src').on('input', function(){ clearTimeout(t); t = setTimeout(function(input) { $('#text-dest').val($(input).val()); }, 1000, this); }) }(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="text-src" type="text"> &gt;&gt;&gt; <input id="text-dest" type="text"> 

  • Here, what you need! And how to make that in the opposite direction the exact same feature worked? - user193361
  • @ user193361 - likewise. Hang the handler with a different timeout on the second field. - Qwertiy
  • as if in one function? I wanted to use the multi-selector to hang up the function, but how to change the selector in setTimeout I won't catch up - user193361
  • @ user193361, why do it in one function? Bring logic to the jQuery plugin and apply it twice. Another option is to hang data-attributes with a different input on the input. - Qwertiy

I understand you need something like that.

To do this, there is a debounce function that can be found in the Underscore / Lodash libraries. It will be executed only a second after its last call.

 var $first = document.getElementById( 'first' ); var $second = document.getElementById( 'second' ); var debouncedFunction = _.debounce( function() { $second .placeholder = $first.value; }, 1000 ); $first.addEventListener( 'input', debouncedFunction ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> <label>Первое поле <input id='first' /> </label> <br /> <label>Второе поле <input id='second' placeholder='' /> </label> 

We try this:

 $('#enter-text').on('change', function(){ var our_text = $(this).val(); setTimeout (function() { $('#text').val(our_text) }, 1000); }) 
 * { box-sizing: border-box; } .wrapper { margin: 30px auto; text-align: center; } input { border: 2px solid #747474; padding: 15px 30px; outline: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="wrapper"> <input id='enter-text' type="text" /> <p>You entered:</p> <input id="text"> </div> 

  • not that, you get the second input "slows down" for one second, but I need the value in the second form to change one second after the user has finished entering - user193361
  • Sometimes you want to put a comment like that minus ... @ user193361, but what's the difference? UPDATE: Still understood. It is necessary to somehow formulate something clearer. - Qwertiy
  • Then try to change the keyup to change. - NeedHate
  • and still your second input changes its content only after the first loses the focus - user193361