简体   繁体   English

JavaScript setTimeout setInterval

[英]JavaScript setTimeout setInterval

I am writing some code for a website and I want to create a 165px x 2px line that shows up and then disappears and continues to do that to infinity. 我正在为一个网站编写一些代码,我想创建一个165px x 2px的行显示然后消失并继续这样做到无限。 I have wrote this code in JavaScript: 我用JavaScript编写了这段代码:

function sivapokretna() {
        document.getElementById("pokretnasiva").style.width= "165px";
        setTimeout("document.getElementById('pokretnasiva').style.width= '0px';", 4000);
}

function sivo() {
    setInterval(sivapokretna(), 8000);
}

As you can see, in the first function I change the size of the div element from 0 to 165 and then after delay I turn it back to 0. For some reason, it is only done once although I used setInterval in the second function. 正如您所看到的,在第一个函数中,我将div元素的大小从0更改为165,然后在延迟之后将其重新设置为0.出于某种原因,尽管我在第二个函数中使用了setInterval,但它只执行了一次。 Not to be confused, I have done changing with CSS3 3 seconds transition. 不要混淆,我已经完成了CSS3 3秒转换。 Here is the CSS part of the code of the element that is changing. 这是正在改变的元素代码的CSS部分。

#pokretnasiva {
    width: 0px;
    height: 2px;
    background: #ff0000;
    transition: width 3s;
}

You need to pass a reference to the function to setInterval . 您需要将对函数的引用传递给setInterval You are invoking the function so you're actually passing its return value (which is undefined since there is no explicit return statement). 您正在调用该函数,因此您实际上正在传递其返回值 (由于没有显式的return语句,因此undefined )。

You need to remove the invoking parentheses: 您需要删除调用括号:

setInterval(sivapokretna, 8000);
//                     ^--- No invoking parentheses here!

You are calling the function, running immediately, and then telling setInterval to run undefined (the return value of the function) over and over. 您正在调用该函数,立即运行,然后告诉setInterval一遍又一遍地运行undefined (函数的返回值)。

You need to pass the function , not call the function and pass its return value. 您需要传递函数 ,而不是调用函数并传递其返回值。

Remove the () . 删除()

setInterval(sivapokretna, 8000)

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

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