简体   繁体   English

为什么setInterval一段时间后无法正常工作?

[英]Why setInterval is not working properly after a while?

I have written a javascript code to show users a random quote every 10 second. 我写了一个JavaScript代码,向用户显示每10秒随机的报价。 I use jquery to update the div and setInterval to repeat the action. 我使用jquery更新div和setInterval以重复该操作。 I'm fetching a random quote from a javascript array. 我正在从JavaScript数组中获取随机报价。

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. 但是,当我对此进行测试时,似乎在一段时间(如3-5分钟)后无法正常工作,我有一些jquery效果,例如fadeIn和fadeOut,但它们在报价更改之前执行。 Here is the js code; 这是js代码;

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. 在这种情况下,您要使用的可能是setTimeout而不是setInterval。 I suggest to try this link: http://ejohn.org/blog/how-javascript-timers-work/ 我建议尝试以下链接: http : //ejohn.org/blog/how-javascript-timers-work/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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