延迟运行一个function3秒?

我希望延迟运行此function3秒钟:

 $('#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'); } });  

我遇到的所有示例都涉及在X秒后使用setTimeout或显示元素。 但我不确定这将如何适用于我的function。

使用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); 

你需要使用setTimeout(),因为它被触发一次另一方面setInterval()被触发,直到调用clear interval。

现场演示

 $('#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

setTimeout()方法在指定的毫秒数后调用函数或计算表达式。

的setInterval

setInterval()方法以指定的时间间隔(以毫秒为单位)调用函数或计算表达式。

setInterval()方法将继续调用该函数,直到调用clearInterval()或关闭窗口。

JQuery有自己的.delay()函数。 有关文档: http : //api.jquery.com/delay/

虽然我无法为自己测试这个问题。 这可能会让您知道如何实现这一目标。