为什么setTimeout()只在第一次运行我的代码?

3

我使用这个 JavaScript 代码来打开两张图片并通过点击另一张图片来切换垂直菜单。现在我想用定时器在不点击图片的情况下运行代码。所以我写了这段代码,但它只在第一次运行一次。

我的代码有什么问题?

<script type="text/javascript">
        $(document).ready(function () {
            $("#lista2").slideToggle(1);
            $curtainopen = false;
                        $(".rope").click(function () {
            $(this).blur();
            if ($curtainopen == false) {
                var selected = $(this).val();
                var image = $(".rope");
                image.fadeOut('fast', function () {
                    $("#largeImg").attr('src', 'images/power-on.png');
                    image.fadeIn('fast');
                });

                $(".leftcurtain").stop().animate({ left: '-120px' }, 2000);
                $(".rightcurtain").stop().animate({ left: '120px' }, 2000);

                $("#R").attr('src', 'images/Right.gif');
                $("#L").attr('src', 'images/Left.gif');
                $curtainopen = true;
                $("#lista2").slideToggle(2000);
                $(this).attr('id', '1');
            } else {
                var selected = $(this).val();
                var image = $(".rope");
                image.fadeOut('fast', function () {
                    $("#largeImg").attr('src', 'images/power-off.png');
                    image.fadeIn('fast');
                });

                $(".leftcurtain").stop().animate({ left: '0px' }, 2000);
                $(".rightcurtain").stop().animate({ left: '0px' }, 2000);
                $curtainopen = false;
                $("#lista2").hide();
                $(this).attr('id', '0');
            }
            return false;
                        });
        });

            function startTimer() {
                setTimeout($(".rope").click(), 4000);

            }

    </script>


setTimeout(function(){$(".rope").click()}, 4000); - A. Wolff
4个回答

3
使用此功能在特定时间间隔后执行您的代码。
setInterval(function() {
    $(".rope").click(); // this will execute after every 4 sec.
}, 4000);

使用这个函数在特定的时间延迟后执行您的代码。

 setTimeout(function() {
        $(".rope").click(); // this will execute after 4 sec delay only once.
    }, 4000);

根据你的需求使用上述内容。


1

setTimeout需要一个函数,当你传递$(".rope").click()时,它会立即调用。

使用方式如下:

function startTimer() {
    setTimeout(function () {
        $(".rope").click();
    }, 4000);
}

请在回答时考虑解释问题。 - Benjamin Gruenbaum

0
setTimeout(function() {
    $(".rope").click();
}, 4000);

因为setTimeout需要一个函数,但是$(".rope").click()会立即调用自身(而不是分配一个要调用的函数)。所以你不想调用一个函数,而是要传递它给setTimeout


0
计时器意味着在每个超时后重复执行函数。setTimeOut仅延迟一次函数(在给定的时间(以毫秒为单位)之后)。
function startTimer() {
  //do your stuff
  $(".rope").click();
  //repeats itself after 4 seconds
  setTimeout(startTimer, 4000);
}

不要忘记在文档准备就绪时启动它:

$(document).ready(function () {
  startTimer();
  ...
}

如果您不希望在页面加载时立即调用函数,可以添加初始延迟:

$(document).ready(function () {
  setTimeout(startTimer, 5000); //the timer will start only 5 seconds after page load
  ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接