Home > database >  My javascript function does not loop using setInterval
My javascript function does not loop using setInterval

Time:12-04

I have to create a JS program that changes the title of a page either every 30 seconds or when the user leaves the page. It depends on the word passed in parameter. I call "linear" the function that allows to change the title every 30 seconds and leaving the one that allows it when the user leaves the page.

The leaving function works well but the linear function executes only the first cell of the message array to display. I tried several alternatives but nothing works, could someone explain my error? Here is the code

var titles = ["MyTitle","AlsoMyTitle","MyThirdTitle","TheFourth"];
var timeLaps = 1000; // time in miliseconds
var i = 0;
var ogTitle = document.title;

function mainTitle() {
    document.title = ogTitle;
}
 
function newTitle() {
    document.title = 'Come Back!';
}

function leaving() {
    window.onblur = newTitle;
    window.onfocus = mainTitle;
}

function linear(){
    if (i == 4) {
        i = 0;
    }
    document.title = titleArray[i];
    i  ;
}

function main(animType) {
    if(animType === "leaving") {
        leaving();
    } else if (animType === "linear") {
        setInterval(() => {
            changeTitle('linear')
          }, timeLaps);
    }
} 

main('linear');

Have a good day!

CodePudding user response:

You call your method changeTitle without arguments, yet you didn't handle the case within method when there is no arguments. Try calling it like this:

setInterval(() => {
  changeTitle('linear')
}, timeLaps);

CodePudding user response:

The solution is pretty simple. With the given code, you should switch array titles to titleArray, or switch titleArray to titles. This is because you defined it as following:

var titles = ["MyTitle","AlsoMyTitle","MyThirdTitle","TheFourth"];

and later you used:

document.title = titleArray[i];

With this simple fix, it worked for me in my browser. What I did was the following:

var titleArray = ["MyTitle","AlsoMyTitle","MyThirdTitle","TheFourth"];

CodePudding user response:

Details are commented in example

let initInterval = null; // Define interval method
/* Set a flag to prevent constant "focus" event triggering
 (see lines marked with: ❉) 
*/
let on = false;
let delay = 3000; // 3 seconds for setTimeout method
/* Change to 30000 for 30 second intervals as per OP. 3 seconds
is just for the sake of brevity 
*/
let interval = 3000;
let count = 0; // Define count with initial value 
// Define array of titles
const titles = ["TITLE I", "TITLE II", "TITLE III", "TITLE IV"];

/*
|| Uncomment line A and comment line B as per OP
*/
// const changeTitle = str => document.title = str; // A
const changeTitle = str => document.querySelector("h1").textContent = str; // B

/*
|| Event handler passes (e)vent object by default
|| Redefine initInterval() method
==========================================================
||   wrap source of setInterval() in an anonymous function so that changeTitle() 
||   can pass the parameter >titles[count  ]< 
||   Note: >count< is incremented on line C.
==========================================================
||   If >count< exceeds the last index of >titles< array, reset >count<
||   Invoke changeTitle(), passing the string at the current index
||   of >titles< array
|| Repeat above every >interval< ms
*/
const go = e => {
  initInterval = setInterval(() => {
    if (count > titles.length - 1) {
      count = 0;
    }
    changeTitle(titles[count  ]); // C
  }, interval);
}

/*
|| Anonymous event handler triggers when window loads
|❉ Set >on< to true which indicates the user is still on the page.
|| Change title to it's welcome message
|| Start go(e) in >delay< ms
*/
window.onload = e => {
  on = true; // ❉
  changeTitle("Loaded");
  setTimeout(go, delay);
}

/*
|| Anonymous event handler triggers when user focuses on window.
|❉ If the >on< flag is false...
||   change the title to the focused message
||   start go(e) in >delay< ms
|❉  set >on< to true. This ensures that the only "focus" event that
||   the event handler gets triggered by is when the user focuses after 
||   a "blur" event
*/
window.onfocus = e => {
  if (!on) { // ❉
    changeTitle("Focused");
    setTimeout(go, delay);
    on = true; // ❉
  }
}
/*
|| Anonymous event handler triggers when the user leaves the window.
|❉ Set the >on< flag to false indicating that the user has left the page
|| Change to title to a leaving message
|| Remove the interval method
*/
window.onblur = e => {
  on = false; // ❉
  changeTitle("Unfocused");
  clearInterval(initInterval);
}
<h1></h1>

  • Related