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?
Note that
setTimeoutandsetIntervalare very different functions:setTimeoutwill execute the code once, after the timeout.setIntervalwill 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)orclearInterval(tid)respectively.So, depending on what you want to do, you have two valid choices:
or
Both are very common ways of achieving the same.