简体   繁体   中英

Javascript code not working properly(works for some time and crashes)

I've made a javascript slideshow for text but it gets bugged after a couple of loops. This is what it should be like(don't mind the cursor in gif):

This is what happens after a couple of loops:

The Javascript code:

var quote_array = [
    "Aš supratau, kad kuo daugiau dirbu,<br/>tuo labiau man sekasi.",
    "Dirbdamas sau malonų darbą<br/>pasieki tobuliausių rezultatų.",
    "Tikras darbas yra darbas<br/>kurio tu nemėgsti."
    ];
var quoteName_array = [
    "-Tomas Džefersonas",
    "-Aristotelis",
    "-Bilas Watersonas"
    ];
var quote_i = Math.floor(Math.random()*quote_array.length);
var quote_elem;
var quoteName_elem;
var patikrinti
function quoteNext()
{
    quote_i = Math.floor(Math.random()*quote_array.length);
    if(patikrinti==quote_i)
    {
        quoteNext();
    }
    quote_elem.style.opacity = 0;
    quoteName_elem.style.opacity = 0;
    setTimeout("quoteSlide()",1100);
}
function quoteSlide()
{
    patikrinti = quote_i;
    quote_elem.innerHTML = quote_array[quote_i];
    quoteName_elem.innerHTML = quoteName_array[quote_i];
    quote_elem.style.opacity = 1;
    quoteName_elem.style.opacity = 1;
    setTimeout("quoteNext()",13900);
}

I didn't see the recurion at first, but in quoteNext() you're (randomly) calling quoteNext() a second time - which will add another setTimeout("quoteSlide()",1100) so over time more and more "loops" are running in parallel, leading to total flickering in the end. Change your function to

function quoteNext() {
    quote_i = Math.floor(Math.random()*quote_array.length);
    if (patikrinti==quote_i) {
        quoteNext(); // try again
    } else { // but do not continue
        quote_elem.style.opacity = 0;
        quoteName_elem.style.opacity = 0;
        setTimeout(quoteSlide, 1100); // pass functions, not code strings
    }
}

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