Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SetInterval is repeating only one time. How to fix it?

I'm trying about ul will moving about 40px to top every second. I was trying many solutions on stackoverflow, but nothing helped.

That's my code

setInterval(function() {
  $("#ul_news").animate({
    marginTop: -40
  }, 300);
}, 1000);
#ul_news {
  /*position: absolute;
  top: 0;
  left: 100px;
  z-index: 20;*/
}
#ul_news li {
  z-index: 20;
  color: black;
  list-style: none;
  padding-bottom: 50px;
}
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

  <ul id="ul_news">
    <li class="active">ahoj2</li>
    <li class="non_active1">ahoj3</li>
    <li class="non_active2">ahoj4</li>
    <li class="non_active3">ahoj5</li>
  </ul>
like image 604
Honza Sedloň Avatar asked Sep 15 '15 16:09

Honza Sedloň


People also ask

How do I repeat setInterval?

You will notice a simple trick: repeat = repeat || setInterval(reduce, 1000); This will ensure multiple intervals are not registered.

How do you run setInterval 5 times?

“setinterval for 5 times” Code Answer'svar intervalID = setInterval(alert, 1000); // Will alert every second. // clearInterval(intervalID); // Will clear the timer. setTimeout(alert, 1000); // Will alert once, after a second.

How do you stop a setInterval loop?

Answer: Use the clearInterval() Method The setInterval() method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.

Do I need to clear setInterval?

SetInterval() does not change the speed that you pass it. If whatever it is doing speeds up each time that you call SetInterval(), then you have multiple timers which are running at the same time, and should open a new question. Make sure you are really stopping it.


1 Answers

You need to use -40 to -=40px or -=40. -40 will just set the margin-top as -40px, if you want to decrease then you need to use like -=40

setInterval(function() {
  $("#ul_news").animate({
    marginTop: '-=40px'
  }, 300);
}, 1000);
#ul_news {
  /*position: absolute;
  top: 0;
  left: 100px;
  z-index: 20;*/
}
#ul_news li {
  z-index: 20;
  color: black;
  list-style: none;
  padding-bottom: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

  <ul id="ul_news">
    <li class="active">ahoj2</li>
    <li class="non_active1">ahoj3</li>
    <li class="non_active2">ahoj4</li>
    <li class="non_active3">ahoj5</li>
  </ul>

Animated properties can also be relative. If a value is supplied with a leading += or -= sequence of characters, then the target value is computed by adding or subtracting the given number from the current value of the property.

Taken from http://api.jquery.com/animate/#animation-properties

like image 78
Pranav C Balan Avatar answered Nov 04 '22 03:11

Pranav C Balan