I have a website that uses javascript to randomly display a list of quotes. I’ve used this same script across 7-8 other sites without issue, but on this current site it just crashes the browser after a few seconds.
I did have a similar problem which was due to the javascript being called on pages that didn’t feature quotes, but I fixed this by moving the javascript into the same ‘includes’ file as the quotes (meaning one can never be called without the other)
The site is on the same server space as the other and the files are exactly the same, so I can’t work out why this site is having a problem and the others aren’t…
Here is the script…
<ul id="quote">
<?php perch_content('Testimonials'); ?>
</ul>
<script type="text/javascript">
this.randomtip = function() {
var pause = 5000; // define the pause for each tip (in milliseconds) Feel free to make the pause longer so users can have time to read the tips :)
var length = $("#quote li").length;
var temp = -1;
this.getRan = function() {
// get the random number
var ran = Math.floor(Math.random() * length) + 1;
return ran;
};
this.show = function() {
var ran = getRan();
// to avoid repeating tips we need to check
while (ran == temp) {
ran = getRan();
};
temp = ran;
$("#quote li").hide();
$("#quote li:nth-child(" + ran + ")").fadeIn(500);
};
// initiate the script and also set an interval
show();
setInterval(show, pause);
};
$(document).ready(function() {
randomtip();
});
</script>
Thanks in advance guys!
You only have one quote, which means that
getRan()is always going to return the same value (1). Sincetempis set to the previous value, you get an endless loop here:If you wrap it in a safety-check like this, it should work.