简体   繁体   中英

Why setInterval is not working properly after a while?

I have written a javascript code to show users a random quote every 10 second. I use jquery to update the div and setInterval to repeat the action. I'm fetching a random quote from a javascript array.

But when i tested this, it seems, it is not working properly after a while (like 3-5 mins) , I have some jquery effects like fadeIn and fadeOut but they are executed before the quote changes. Here is the js code;

var quotes = [
    "Some String",
    "Some String",
    "Some String"
];

$(function() {
    var $rand = $('div#randomQuote > p');
    var random_quote = quotes[Math.floor(Math.random() * quotes.length)];     
    $rand.html(random_quote);
    $rand.animate( {"opacity" : 0}, 0);
    $rand.animate( {"opacity" : 1}, 500);
    $rand.delay("9000");
    $rand.animate( { "opacity" : 0 }, 500 );    
});


function randomQuote () {
    var $rand = $('div#randomQuote > p');
    var random_quote = quotes[Math.floor(Math.random() * quotes.length)]; 
    $rand.html(random_quote);
    $rand.animate( {"opacity" : 1}, 500 );
    $rand.delay("9000");
    $rand.animate ( {"opacity" : 0}, 500 );
}

$(function () {
    setInterval(randomQuote, 10000);
});

Although I'm not sure, I think, these lines take some time to calculate and it breaks the loop.

var $rand = $('div#randomQuote > p');
var random_quote = quotes[Math.floor(Math.random() * quotes.length)]; 

Q: How can i improve this code to get it working as expected?

Thanks in advance.

That way your queue of events will grow indefinitely. What you want to use in this case is probably setTimeout instead of setInterval. I suggest to try this link: http://ejohn.org/blog/how-javascript-timers-work/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM