1

I read that setTimeout is less cpu resources intensive than setInterval. This is my main reason to switch to setTimeout.

This is the code of my ticker which is working perfectly fine, but I can't figure it out how make it work with setTimeout instead of setInterval

function tick() {
  $('#ticker li:first').slideUp(1000, function() {
    $(this).appendTo($('#ticker')).slideDown(1000);
  });
}
setInterval(function() {
  tick()
}, 9000);
empiric
  • 7,825
  • 7
  • 37
  • 48
A Listorne
  • 27
  • 1
  • 6

4 Answers4

6

To replace setInterval with setTimeout, change this:

setInterval(function() {
  tick()
}, 9000);

to:

setTimeout(function repeat() {
  tick();
  setTimeout(repeat, 9000);
}, 9000);

However, setTimeout used in this repeated way will not use less resources. On the contrary, since you have to call setTimeout repeatedly, there is a slight extra overhead compared to your original code.

trincot
  • 317,000
  • 35
  • 244
  • 286
2

When you want to use the setTimeout()-function you have to call your function recursevly (with an inital call onload or whatever):

function tick()
{
    $('#ticker').append('<span>tick</span>');
    setTimeout(tick, 1000);
}
tick();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ticker">

</div>
empiric
  • 7,825
  • 7
  • 37
  • 48
  • I tried to follow your code, but it didn't work on mine, I guess I am doing something wrong when I try to emulate your line, thank you anyway – A Listorne Jun 21 '16 at 18:52
1

var ticksCount = 0;

function tick() {
  $('#ticker li:first').slideUp(1000, function() {
    $(this).appendTo($('#ticker')).slideDown(1000);
  });
}

var t = setInterval(function() {
  tick()
  if (ticksCount > 10) {
    clearInterval(t);
  }

}, 1000);

Here is a great tutorials which can help you:

http://www.w3schools.com/js/js_timing.asp

https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval

Adizbek Ergashev
  • 732
  • 8
  • 17
0

You can replace setInterval to setTimeout by calling setTimeout inside your tick function, passing it recursively:

function tick() {
  $('#ticker li:first').slideUp(1000, function() {
    $(this).appendTo($('#ticker')).slideDown(1000);
  });
  setTimeout(tick, 9000);
}
tick();
fmilani
  • 521
  • 2
  • 9