Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop timer in JavaScript

I need to execute a piece of JavaScript code say, each 2000 milliseconds.

setTimeout('moveItem()',2000) 

The above will execute a function after 2000 milliseconds, but won't execute it again.

So inside my moveItem function I have:

function moveItem() {     jQuery(".stripTransmitter ul li a").trigger('click');     setInterval('moverItem()',2000); } 

This does not work because I want to execute the trigger click jQuery piece of code each interval of 2000 milliseconds, but right now it is being called all the time and the script needs to be interrupted. Besides that, I feel this is very bad quality coding... How would you guys solve this?

like image 917
Marcos Buarque Avatar asked Jan 25 '10 15:01

Marcos Buarque


People also ask

Is there a timer in JavaScript?

There are two timer functions in JavaScript: setTimeout() and setInterval() . The following section will show you how to create timers to delay code execution as well as how to perform one or more actions repeatedly using these functions in JavaScript.


2 Answers

Note that setTimeout and setInterval are very different functions:

  • setTimeout will execute the code once, after the timeout.
  • setInterval will execute the code forever, in intervals of the provided timeout.

Both functions return a timer ID which you can use to abort the timeout. All you have to do is store that value in a variable and use it as argument to clearTimeout(tid) or clearInterval(tid) respectively.

So, depending on what you want to do, you have two valid choices:

// set timeout var tid = setTimeout(mycode, 2000); function mycode() {   // do some stuff...   tid = setTimeout(mycode, 2000); // repeat myself } function abortTimer() { // to be called when you want to stop the timer   clearTimeout(tid); } 

or

// set interval var tid = setInterval(mycode, 2000); function mycode() {   // do some stuff...   // no need to recall the function (it's an interval, it'll loop forever) } function abortTimer() { // to be called when you want to stop the timer   clearInterval(tid); } 

Both are very common ways of achieving the same.

like image 175
Miguel Ventura Avatar answered Sep 28 '22 06:09

Miguel Ventura


setInterval(moveItem, 2000); 

is the way to execute the function moveItem every 2 seconds. The main problem in your code is that you're calling setInterval inside of, rather than outside of, the callback. If I understand what you're trying to do, you can use this:

function moveItem() {     jQuery('.stripTransmitter ul li a').trigger('click'); }  setInterval(moveItem, 2000); 

N.B.:Don't pass strings to setTimeout or setInterval - best practice is to pass an anonymous function or a function identifier (as I did above). Also, be careful to not mix single and double quotes. Pick one and stick with it.

like image 40
Matt Ball Avatar answered Sep 28 '22 04:09

Matt Ball