Sync a message with a stopwatch.. setTimeout not working

I’m pretty lost on this. I’m trying to sync a stopwatch which will eventually sync with a song. I want a “up” or “down” message to show up based on lyrics in the song. If you’re curious its Flower – Moby for the Sally Push Up Challenge.

I’m new to coding and this is just an idea to learn to code.

This is the plunker: using Angular 2. I’m actually going to use Ionic 2.

Here is what I’ve tried and why I don’t think it works:

The main function for the up/down message is upDown();

My initial idea was to create an array of time intervals then pass that in to setTimeout.

I referenced this stackoverflow question on how to loop through an array and usung setTimeout.

I was pretty happy when it worked but then I played around with the intervals. That’s when I learned why its important to know that setTimeout is asynchronous. Also, setTimeout doesn’t stop looping. I think I have to do a clearTimeout or something.

My next idea is to somehow track the stopwatch time and say


if (this.time === 1000) {this.message= "up"}
if (this.time === 2000) {this.message= "down"}

However, I’m failing pretty bad at it. My attempt isn’t in that plunker link since I haven’t gotten close.

Overall there is about ~60 up down actions and there are about 5 unique intervals of time but its all pretty random.

Here is the upDown() code if you don’t want to look at plunker:

  upDown() {
    this.toggle() //starts the stopwatch
    let action: boolean = false;
    for (let i = 0; i < this.intervals.length; i++) {
      ((index) => {
        setTimeout(() => {
          if (action) {
            this.message = "down";
            action = false;
          } else {
            this.message = "up";
            action = true;
        }, index);

This is a work in progress…. IF anyone is wondering why I have functions that have Srvc in them is because I eventually move them in to a service.

Leave a Reply

Notify of