1

I am trying to build a ludo game using JavaScript & Jquery. So I want the pieces to move step by step. So for that, I wrote this code -

        function moveHorse() {
    
        $('td > img').click(function(event){

    
            // ludo baby steps 
            newfunc = setInterval(function(){
              //Some Code
            },300);
            setTimeout(function(){
                clearInterval(newfunc);
            }, randomDice*300);
        });
    }

The code is working really well. Interval is stopped based on the dice number. But it works only for one time for each player.

When the user clicks on the pieces for the second time the interval is set but it never stops. I found the issue and it's happening bcoz, after the first try, the Interval is executed multiple times in a single execution.

I just want to know how I can fix it.

Please check this video to better understand my issue - https://youtu.be/7d8A8qB5TG8

Vishal Lohar
  • 51
  • 1
  • 5
  • Looks like scoping perhaps - if you have a `var` before `newfunc` does it work better? or do you need reference to that interval somewhere else other than in the cancel timeout? – josh.trow Mar 07 '22 at 05:02
  • @josh.trow **newfunc** is only used inside the **moveHorse()** function. I ran the code again after adding var but still facing the same issue. – Vishal Lohar Mar 07 '22 at 05:10
  • @josh.trow You can watch this video - https://youtu.be/7d8A8qB5TG8 to see what's happening. – Vishal Lohar Mar 07 '22 at 05:15

1 Answers1

0

The problem was multiple function executions at one time. During the first move, the moveHorse function was executed only once. But after that, it was executed 3-7 times on every click.

I found one Stackoverlfow answer that solved my issue. Link of the answer - Javascript - prevent function from executing multiple times

Vishal Lohar
  • 51
  • 1
  • 5