Delay running a function for 3 seconds?

放肆的年华 提交于 2019-12-24 14:12:33

问题


I'm looking to delay running this function for 3 seconds:

<script type="text/javascript">
$('#FormsPageID table tr:nth-child(12) td:nth-child(2) div span span input')
  .on('focus', function(){
      var $this = $(this);
      if($this.val() == '4/11/2013'){
          $this.val('');
      }
  })
  .on('blur', function(){
      var $this = $(this);
      if($this.val() == ''){
          $this.val('4/11/2013');
      }
  });
</script>

The examples I've come across all involve using setTimeout to or show an element after X seconds. But I'm unsure how that would apply to my function.


回答1:


Use setTimeout :

setTimeout(function(){$('#FormsPageID table tr:nth-child(12) td:nth-child(2) div span span input')
 .on('focus', function(){
      var $this = $(this);
      if($this.val() == '4/11/2013'){
          $this.val('');
      }
  })
  .on('blur', function(){
      var $this = $(this);
      if($this.val() == ''){
          $this.val('4/11/2013');
      }
  });}, 3000);



回答2:


You need to use setTimeout() as it is fired once on the other hand setInterval() is triggered until clear interval is called.

Live Demo

$('#FormsPageID table tr:nth-child(12) td:nth-child(2) div span span input')
   .on('focus', function(){
    var $this = $(this);
    if($this.val() == '4/11/2013'){
       setTimeout(function(){ 
             $this.val('4/11/2013');
       }, 3000); 
     }
}).on('blur', function(){
      var $this = $(this);
      if($this.val() == ''){
          setTimeout(function(){ 
             $this.val('4/11/2013');
          }, 3000); 
      }
});

setTimeout

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

setInterval

The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).

The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.




回答3:


JQuery has its own .delay() function. For documentation: http://api.jquery.com/delay/

Although I'm not able to test this for myself atm. This might give you a small idea how to accomplish this.

<script type="text/javascript">
$('#FormsPageID table tr:nth-child(12) td:nth-child(2) div span span input').delay(3000).focus(function () { 
    var $this = $(this);
    if($this.val() == '4/11/2013'){
        $this.val('');
    }
  }).delay(3000).blur(function() {
    var $this = $(this);
    if($this.val() == ''){
        $this.val('4/11/2013');
    }
  });
</script>


来源:https://stackoverflow.com/questions/15951708/delay-running-a-function-for-3-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!