如何在Prototype中正确使用setTimeout或setInterval?

时间:2017-10-29 14:16:21

标签: javascript

我试图获得new Date()并使用原型自动显示div中的时间。但它不起作用。

我希望它如何工作

<div></div>

Element.prototype.startTime

div.startTime('a word')


<div> 00:00:00 </div>第二次更新



我拥有什么

&#13;
&#13;
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');
&#13;
<div id="display"></div>
&#13;
&#13;
&#13;



它是如何工作的

&#13;
&#13;
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');
&#13;
<div id="display"></div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

setTimeout中使用prototype的主要问题是使用this

所以只需设置that = this并使用that变量......一切都会很好用。

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>