Allen Marshall
Allen Marshall

Reputation: 391

How to properly use setTimeout or setInterval within a Prototype?

I'm trying to get a new Date() and show the time in a div automatically with a prototype. But it's not working.

How I wish for it to work

<div></div>

Element.prototype.startTime

div.startTime('a word')


<div> 00:00:00 </div> Updates by the second



What I have

function checkTime(i) {
  return (i < 10) ? "0" + i : i;
}

setTimeout(Element.prototype.startTime = function(t) {
  var today = new Date(),
    h = checkTime(today.getHours()),
    m = checkTime(today.getMinutes()),
    s = checkTime(today.getSeconds());
  if (t === 'time') {
    this.innerHTML = h + ":" + m + ":" + s;
  }
  if (t === 'minutes') {
    this.innerHTML = m;
  }
  if (t === 'seconds') {
    this.innerHTML = s;
  }
}, 500);// Not Updating Properly

document.getElementById('display').startTime('time');
<div id="display"></div>




How it's suppose to work

function checkTime(i) {
  return (i < 10) ? "0" + i : i;
}

function startTime(t) {
  var today = new Date(),
    h = checkTime(today.getHours()),
    m = checkTime(today.getMinutes()),
    s = checkTime(today.getSeconds());

  div = document.getElementById('display')

  if (t === 'time') {
    div.innerHTML = h + ":" + m + ":" + s;
  }
  if (t === 'minutes') {
    div.innerHTML = m;
  }
  if (t === 'seconds') {
    div.innerHTML = s;
  }

  setTimeout(function() {
    startTime(t)
  }, 500);
};
startTime('time');
<div id="display"></div>

Upvotes: 0

Views: 100

Answers (1)

Monwell Partee
Monwell Partee

Reputation: 718

Your main problem for using setTimeout in prototype was using this

So just set that = this and use that variable… everything will work beautifully.

function checkTime(i) {
  return (i < 10) ? "0" + i : i;
}

Element.prototype.Today = function(t) {
  let that = this
  today = new Date()
  h = checkTime(today.getHours());
  m = checkTime(today.getMinutes());
  s = checkTime(today.getSeconds());

  if (t === 'time') {
    that.innerHTML = h + ":" + m + ":" + s;
  }
  if (t === 'minutes') {
    that.innerHTML = m;
  }
  if (t === 'seconds') {
    that.innerHTML = s;
  }
  setTimeout(function() {
    that.Today(t)
  }, 500);

  return this
};


div = document.getElementById('display')
div.Today('time')
<div id="display"></div>

Upvotes: 1

Related Questions