简体   繁体   English

我的javascript function不循环使用setInterval

[英]My javascript function does not loop using setInterval

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.我必须创建一个 JS 程序,每 30 秒或当用户离开页面时更改页面的标题。 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.我将 function 称为“线性”,它允许每 30 秒更改一次标题,并在用户离开页面时保留允许更改的标题。

The leaving function works well but the linear function executes only the first cell of the message array to display.离开的 function 运行良好,但线性 function 仅执行要显示的消息数组的第一个单元格。 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!祝你有美好的一天!

The solution is pretty simple.解决方案非常简单。 With the given code, you should switch array titles to titleArray, or switch titleArray to titles.使用给定的代码,您应该将数组标题切换为 titleArray,或将 titleArray 切换为标题。 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"];

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>

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:你在没有 arguments 的情况下调用你的方法 changeTitle,但是当没有 arguments 时你没有处理方法内的情况。尝试这样调用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM