My Objective:
To generate a random number
To start a timer that counts to this number and then displays a button with a random margin
To stop the first timer and start another when the button is clicked
To calculate the time elapsed between the appearance of the button and its click
I attempted to create a boolean field in a component class, so that when the button is clicked, the boolean changes to true. Then, the timer checks this boolean value at each tick, deleting the button and restarting the initial timer if it's true.
The issue arises when the button is clicked because the 'clicked' field doesn't change as expected. What am I missing here?
import { Component, OnInit } from '@angular/core';
import {TimerObservable} from "rxjs/observable/TimerObservable";
@Component({
selector: 'app-gra',
templateUrl: './gra.component.html',
styleUrls: ['./gra.component.css']
})
export class GraComponent implements OnInit {
randNum: any;
timerSub: any;
userTimerSub: any;
clicked: boolean;
constructor() { }
ngOnInit() {
this.randNum = 3+ Math.floor(Math.random()*3);
console.log('random: ' + this.randNum)
this.clicked = false;
let timer = TimerObservable.create(0, 1000);
this.timerSub = timer.subscribe( d => this.timerFunction(d) );
}
timerFunction(d){
console.log(d);
if(d === this.randNum){
var btn = document.createElement("BUTTON"); // Create a <button> element
var t = document.createTextNode("CLICK ME"); // Create a text node
btn.appendChild(t);
btn.id = "button"
let margin = Math.floor(Math.random()*500);
document.body.appendChild(btn); // Append <button> to <body>
btn.setAttribute('style', 'margin-top: ' + margin + "px;");
document.getElementById("button").addEventListener("click", this.buttonClick.bind(this));
this.timerSub.unsubscribe();
let timer = TimerObservable.create(0, 1000);
this.userTimerSub = timer.subscribe( d => this.userTimerFunction(d) );
this.randNum = 3 + Math.floor(Math.random()*3);
console.log('new rand: ' + this.randNum)
}
}
userTimerFunction(d){
console.log('user' + d)
console.log(this.clicked)
if(this.clicked == true){
console.log('It took you ' + d + 'seconds');
this.userTimerSub.unsubscribe();
var element = document. getElementById("button");
element.parentNode.removeChild(element);
let timer = TimerObservable.create(0, 1000);
this.timerSub = timer.subscribe( d => this.timerFunction(d) );
}
}
buttonClick(){
console.log('clicked: ' + this.clicked);
this.clicked = true;
}
}