JB.
JB.

Reputation: 913

jQuery add timeout to random text array

I have a link that changes text every time its clicked but I am trying to find a way for it to automatically switch to the next variable after a period of time, sort of like a rotator.

This is what I have:

    $(document).ready( function() {
    var quotes = [
        'Link 1',
        'Link 2',
        'Link 3',
        'Link 4',
        'Link 5',
        'Link 6'
    ];

    function loadQuote(i) {
        return quotes[i];
    }

    function randNumber() {
        return Math.floor( Math.random() * quotes.length );
    }
    $('#button-reload').click(function() {
            $(this).html(loadQuote(randNumber()));
    });
    $('#button-reload').html(loadQuote(randNumber()));
});​

and here is a jsfiddle

any ideas?

Upvotes: 2

Views: 373

Answers (2)

JamesSwift
JamesSwift

Reputation: 863

$(document).ready( function() {
    var quotes = [
        'Link 1',
        'Link 2',
        'Link 3',
        'Link 4',
        'Link 5',
        'Link 6'
    ];

    var $theLink = $('#button-reload');

    function loadQuote(i) {
        return quotes[i];
    }

    function randNumber() {
        return Math.floor( Math.random() * quotes.length );
    }

    function changeTheQuote() {
        $theLink.html(loadQuote(randNumber())); 
    }

    var interval = window.setInterval(function(){
        changeTheQuote();
    }, 3000); 

    $theLink.click(function() {
        window.clearInterval(interval);
        changeTheQuote();
        interval = window.setInterval(function(){
            changeTheQuote();
        }, 3000); 
    });
});

Upvotes: 2

Habibillah
Habibillah

Reputation: 28695

Try use window.setInterval() like code bellow:

$(document).ready( function() {
    var quotes = [
        'Link 1',
        'Link 2',
        'Link 3',
        'Link 4',
        'Link 5',
        'Link 6'
    ];

    function loadQuote(i) {
        return quotes[i];
    }

    function randNumber() {
        return Math.floor( Math.random() * quotes.length );
    }

    var interval = window.setInterval(function(){
        $('#button-reload').html(loadQuote(randNumber()));            
    }, 3000);   

    $('#button-reload').click(function() {
        $(this).html(loadQuote(randNumber()));

        //uncomment line bellow to stop intarval when button clicked.
        //window.clearInterval(interval);
    });  
});

Upvotes: 3

Related Questions