Advertisement
Guest User

Untitled

a guest
Apr 26th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. class Stopwatch {
  2. constructor(el) {
  3. this.target = document.querySelector(el);
  4. this.start = this.start.bind(this);
  5. this.stop = this.stop.bind(this);
  6. this.active = false;
  7. this.ms = 0;
  8. this.intervalId = null;
  9.  
  10. this.render();
  11. this.target.addEventListener('click', this.onClick.bind(this));
  12. }
  13.  
  14. render() {
  15. const frag = document.createDocumentFragment();
  16. const h1 = document.createElement('h1');
  17. h1.innerText = '0';
  18. const startButton = this._genButton('start');
  19. const stopButton = this._genButton('stop');
  20. const resetButton = this._genButton('reset');
  21.  
  22. frag.appendChild(h1);
  23. frag.appendChild(startButton);
  24. frag.appendChild(stopButton);
  25. frag.append(resetButton);
  26.  
  27. this.target.appendChild(frag);
  28. }
  29.  
  30. start() {
  31. if (!this.active) {
  32. this.active = !this.active;
  33. this.intervalId = setInterval(() => {
  34. this.ms += 1;
  35. this.target.firstElementChild.innerText = this.ms;
  36. }, 1)
  37. }
  38.  
  39. return;
  40. }
  41.  
  42. stop() {
  43. if (this.active) {
  44. this.active = !this.active;
  45. clearInterval(this.intervalId);
  46. }
  47.  
  48. return;
  49. }
  50.  
  51. reset() {
  52. this.stop();
  53. this.ms = 0;
  54. this.target.firstElementChild.innerText = this.ms;
  55. }
  56.  
  57. _genButton(name) {
  58. const genericButton = document.createElement('button');
  59. genericButton.className = name;
  60. genericButton.innerText = name;
  61.  
  62. return genericButton;
  63. }
  64.  
  65. onClick(e) {
  66. if (e.target.matches('.start')) {
  67. this.start();
  68. }
  69.  
  70. if (e.target.matches('.stop')) {
  71. this.stop();
  72. }
  73.  
  74. if (e.target.matches('.reset')) {
  75. this.reset();
  76. }
  77.  
  78. return;
  79. }
  80. }
  81.  
  82. const s = new Stopwatch('.target');
  83. const c = new Stopwatch('.target2');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement