Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Having problem with a little flashing metronome project I'm working on.

I'm using .setInterval to flash the screen between two colors and HTML buttons to increase or decrease the flash rate. The problem lies in that my variables for the increased or decreased flash rate functions call the original flash rate function and everything gets convoluted. I've tried a bunch of ways to address this and I can't get it right; too new to JS. Any thoughts?

As a secondary question if you have the time.... What would be a better approach for adjusting flash rate? Form? Drop down menu? Etc.

Here is the link to my codepen http://codepen.io/Fedreg/pen/aNJojy

Thanks for any help!!

2 Answers

akak
akak
29,444 Points

Hi, The problem is that you don't stop any interval, just add one after another. You need to assign interval to a variable and then you can clear interval.

var x = 500;
var flashStep = 1;
var myInterval;

function flash() {
  if (flashStep == 1) {
    document.bgColor = "#51cfff";
    flashStep = 2;
  } else {
    document.bgColor = "#333";
    flashStep = 1;
  }
}

function faster() {
  window.clearInterval(myInterval);
  myInterval = window.setInterval(flash, x -= 50);
}

function slower() {
  window.clearInterval(myInterval);
  myInterval = window.setInterval(flash, x += 50);
}

myInterval = window.setInterval(flash, x);

Thanks akak!! I tried a solution like that but couldn't quite get it right; was over complicating it. Thanks again!