在开始一个将循环自身的函数之前延迟6秒,小,不工作,为什么

Delay 6 seconds before beginning a function that will loop itself, small, not working, why?

本文关键字:延迟 函数 6秒 工作 为什么 开始 一个 循环      更新时间:2023-09-26

我试图在heartColor(e)函数开始之前创建一个6秒的延迟,然后函数将继续循环。我不明白为什么它立即启动功能,而没有等待它应该等待的6秒,我做错了什么?

function heartColor(e) {
    e.animate({
        color: '#7ea0dd'
    }, 1000).animate({
        color: '#986db9'
    }, 1000).animate({
        color: '#9fc54e'
    }, 1000, function(){
        heartColor(e)
    })
}
$('.something').hover(function(){
    setTimeout(heartColor($(this)), 6000);
})

setTimeout()函数希望其第一个参数是函数引用(或字符串,但出于多种原因不建议使用)。您不是在给它传递函数引用,而是在调用heartColor()函数并将结果传递给setTimeout()。因此,该函数立即执行,六秒钟后什么也没发生,因为返回值未定义,所以setTimeout()没有任何可处理的内容。

试试这个:

$('.something').hover(function(){
    var $this = $(this);
    setTimeout(function() {
      heartColor($this);
    }, 6000);
})

我之所以包含一个匿名函数作为setTimeout的参数,是因为您对heartColor()的调用需要传递一个参数。如果它没有任何参数,你可以这样做:

setTimeout(heartColor, 6000);

请注意,heartColor后面没有括号,它可以在不调用的情况下引用函数,以便稍后setTimeout为您调用它。但是您不能同时获得对该函数的引用和提供参数,因此需要将调用封装在另一个函数中。你可以这样做:

var $this = $(this);
function callHeartColor() {
   heartColor($this);
}
setTimeout(callHeartColor, 6000);

我最初使用匿名功能的答案有点简单,而且(大多数人觉得)更方便。

我之所以创建一个变量$this,是因为this关键字在JavaScript中的工作方式,这取决于函数的调用方式。如果您只是在匿名函数(或callHeartColor()函数)中说heartColor($(this)),则this不会是悬停在上面的元素。

您正在调用函数heartColor,而不是将其作为参数传递。你必须做:

$('.something').hover(function(){
    setTimeout(function(){heartColor($(this))}, 6000);
})

您想要的是:

$('.something').hover(function(){
  setTimeout(function() {heartColor($(this));}, 6000);
})