[javascript] 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?

This question is related to javascript jquery

The answer is


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.


It should be:

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

setInterval(f, t) calls the the argument function, f, once every t milliseconds.


I believe you are looking for setInterval()


You should try something like this:

 function update(){
    i++;
    document.getElementById('tekst').innerHTML = i;
    setInterval(update(),1000);
    }

This means that you have to create a function in which you do the stuff you need to do, and make sure it will call itself with an interval you like. In your body onload call the function for the first time like this:

<body onload="update()">

Here the Automatic loop function with html code. I hope this may be useful for someone.

<!DOCTYPE html>
<html>
<head>
<style>
div {
position: relative;
background-color: #abc;
width: 40px;
height: 40px;
float: left;
margin: 5px;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p><button id="go">Run ยป</button></p>
<div class="block"></div>
<script>

function test() {
$(".block").animate({left: "+=50", opacity: 1}, 500 );
   setTimeout(mycode, 2000);
};
$( "#go" ).click(function(){
test();
});
</script>
</body>
</html>

Fiddle: DEMO