1

To keep things simple, let's just say I want the title of the website to increment 1 every second, starting at 0. I know how to do this with JavaScript using setInterval—it's rather straight forward. However, set interval seems to essentially stop working once I've switched to a new tab. I see websites that do this type of periodic updating when not in focus, so I know it's possible. I tried looking through their source code but couldn't figure anything out. So, how does one accomplish this?

Mason
  • 738
  • 7
  • 18

1 Answers1

-1

Well it should be done through renewing the DOM element each time a second passes.

So it could be something like this. FunctionOne(){ setInterval(function(){ var title = document.getElementByTagName('title'); var TimesChanging = "My number or variable"; for(var a = 0; a <= TimesChanging; a++) { title.innerHTML = "My title " + a; } return a; } ,1000)}

In this way each second the cicle updates the title up to a number of times decided by the TimesChanging variable..

And for the problem of not working with a different tab it may depend on the focus of the page, you might say something like:

     <body onfocusout="myFunctionTwo(a)" onfocus="FunctionOne()">

     myFunctionTwo(a) {
     setInterval(
     function(){ 
        var title = document.getElementByTagName('title');
        for (a; a<= variable; a++){
         title.innerHTML = "My title " + a;
          }
       ,1000)};

in this way on the focusing out of the body you pass the parameter a to the second function and in this way you keep on cycling the variable.

  • `.getElementByTagName()` doesn't exist. It's `.getElementsByTagName()` and it doesn't just return a single element, it returns a "live" node list. Because of the live part, it should be avoided in all use cases that don't require that. Instead, use `.querySelector()`. Also, the loop in your code won't work as you think it will. The user would just see the last value of `TimesChanging` every one second. They'd never see all the values in between. – Scott Marcus Feb 02 '19 at 17:20
  • The loop is unnecessary because the interval acts as the loop. Just change the title in the interval call back function and keep the counting variable outside of the interval call. Also, don't use `.innerHTML` if you aren't setting/getting any HTML. Use `.textContent`. – Scott Marcus Feb 02 '19 at 18:27