setTimeout是否在第一次运行时没有延迟?

时间:2018-12-12 19:33:07

标签: jquery

我具有此功能,我想在不等待超时5000的情况下首次执行它。

如何在没有第一次延迟的情况下执行setTimeout函数?

function slideSwitch() {

    var $gallery = $('#slideshow'),
    $active = $gallery.find('img:visible'),
    $next = $active.next().length ? $active.next() : $gallery.find('img').first();

    setTimeout(function() {

        $active.hide();
        $next.fadeIn('1000', slideSwitch);

    }, 5000);

};

3 个答案:

答案 0 :(得分:1)

在隐藏/淡入淡出操作之后移动setTimeout调用:

function slideSwitch() {
    var $gallery = $('#slideshow'),
        $active = $gallery.find('img:visible'),
        $next = $active.next().length ? $active.next() : $gallery.find('img').first();
    $active.hide();
    $next.fadeIn('1000', () => setTimeout(slideSwitch, 5000));
}

答案 1 :(得分:0)

function slideSwitch() {

var $gallery = $('#slideshow'),
$active = $gallery.find('img:visible'),
$next = $active.next().length ? $active.next() : $gallery.find('img').first();
var fooBar = function() {

    $active.hide();
    $next.fadeIn('1000', slideSwitch);

};
fooBar();
setTimeout(fooBar, 5000);
};

答案 2 :(得分:0)

定义一个函数而不是匿名函数,并在setTimeout调用它之前。

function fnc ...

fnc();
setTimeout(fnc, 1000);