Adding a Quiz Timer, Fade Out/Skip to the next if timer reaches 0

别说谁变了你拦得住时间么 提交于 2019-12-05 04:46:20

This is moderately tricky for a first jQuery project.

The knack (in this solution) is to factor out a goNext function that can be called in two ways - in response to a click event and in response to a 15 second setTimeout(), not setInterval().

$(function(){
    var questionTimeout = null;

    function goNext($el) {
        clearTimeout(questionTimeout);
        var $next = $el.next();
        $el.fadeOut(500, function() {
            if($next.length > 0) {
                $next.fadeIn(500, function() {
                    questionTimeout = setTimeout(function() {
                        goNext($next);
                    }, 15000);
                });
            }
            else {
                afterLastQuestion();
            }
        });
    }
    function afterLastQuestion(){
        alert("last question complete");
        $start.show();
    }

    var $superContainer = $("#superContainer").on('click', '.next', function() {
        goNext($(this).closest('.slide-container'));
        return false;
    });

    var $start = $("#start").on('click', function(){
        $(this).hide();
        $superContainer.find(".slide-container")
            .eq(0).clone(true,true)
            .prependTo(superContainer)
            .find(".next").trigger('click');
        return false;
    });
});

DEMO

The process is started by clicking a "start" link, causing the first question to be cloned followed by a simulated click on the clone's "next" link. This ensures that the (actual) first question is treated in exactly the same way as all the others.

I also included a afterLastQuestion() function. Modify its action to do whatever is necessary after the last question is answered (or times out).

You could keep the current question in a variable, resetting it on a next click and in the timer, e.g.

var $current;
superContainer.find('.next').click(function (e) {

    e.preventDefault();
    $(this).parents('.slide-container').fadeOut(500, function () {
        $(this).next().fadeIn(500);
        $current = $(this).next();
    });

});​

You'll just need to set it to your first question on initialisation, and remember to reset your timer on a next click

Also, it's usually preferable to use e.preventDefault() rather than return false.

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