Riley Shaw
Riley Shaw

Reputation: 321

JavaScript function on interval being erratic

I'm working on a personal website and I'm trying to make a small script to change a certain part of the html every few seconds (three seconds at the moment).

It switches the text at the bottom from this:

enter image description here

To this:

enter image description here

EDIT: The entire html.erb page looks like this

<br />
<br />
<br />
<p>I make <strong id="noun"><%= @word %></strong>.</p>

<script>
var words = ["programs", "video games", "software", "music", "board games", "websites"];

var shift = setInterval(function(){ 
    var word = words[Math.floor(Math.random()*words.length)];
    $("#noun").text(word);
}, 3000);

window.onbeforeunload = function() {
   clearInterval(shift);
};
</script>

It works perfectly the first time, but if I go to one of the links in the navbar (for example Resume) and the return home, it acts almost like it has two intervals and will switch words twice as often. This stacks and I can get it to switch words 5 or 6 times faster than it should. However, on refresh, it goes back to normal.

What's the issue and how can I fix it?

Thanks!

Upvotes: 2

Views: 113

Answers (1)

Amit
Amit

Reputation: 843

If it's a SPA, ensure that you're clearing the interval to prevent it from continuing (and prevent memory leaks)

useclearInterval(shift) before you navigate.

Upvotes: 1

Related Questions