Is there a built in function that will enact this DOM manipulation every interval?

Viewed 62

I am trying to have this function run every 2 seconds. So far the 'test' is logging repeatedly but the dom manipulation is occurring successfully once. After that it is not updated with the new time in subsequent intervals. Is there a built in function I am missing to "action/verb" this line? I am using the Moment JS library to retrieve the current time in case that is useful context.

  var domstrings = {
    timebox : '#time',
  }


  let m = moment()
  let currentTime = m.format('h: m: s')



 setInterval(function(){
   console.log('test');
   let currentTime = m.format('h: m: s')
   document.querySelector(domstrings.timebox).textContent = currentTime;
  }, 2000)
1 Answers

The dom manipulation is occurring successfully repeatedly but the data is the same at anytime; that's because you have declared m variable globally and it have a the same value every 2 seconds, you have to move declaration inside of your function...

Like...

var domstrings = {
    timebox : '#time',
}

setInterval(function(){
  let m = moment()
  let currentTime = m.format('h: m: s')
  console.log('test');
  document.querySelector(domstrings.timebox).textContent = currentTime;
}, 2000)
Related