Loop timer in JavaScript

前端 未结 6 937

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

setTimeout(\'moveItem()\',2000)

The above will execute a function

6条回答
  •  被撕碎了的回忆
    2020-11-28 21:26

    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.

提交回复
热议问题