0

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. I have wrote this code in 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. Not to be confused, I have done changing with CSS3 3 seconds transition. Here is the CSS part of the code of the element that is changing.

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

2 Answers 2

1

You need to pass a reference to the function to setInterval. You are invoking the function so you're actually passing its return value (which is undefined since there is no explicit return statement).

You need to remove the invoking parentheses:

setInterval(sivapokretna, 8000);
//                     ^--- No invoking parentheses here!
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it worked! But now there is 8s delay at the beginning... How can I make it start changing right away?
@user1687538 - Just call sivapokretna before calling setInterval. For example: sivapokretna(); setInterval(sivapokretna, 8000);
1

You are calling the function, running immediately, and then telling setInterval to run undefined (the return value of the function) over and over.

You need to pass the function, not call the function and pass its return value.

Remove the ().

setInterval(sivapokretna, 8000)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.