There is a function. An automatic timer is called, which changes the pictures after a certain period of time.

function timer(flag){ var intervalId = setInterval (function(){...} if (flag == 'false') { clearInterval(intervalId); } } 

Call this function with the parameter false

 timer('false'); 

Works and stops.

When I click on the picture, I want to call this function and stop the timer and then restart from the moment I clicked on the picture.
Writing

 $("#cimg2").click(function(event){ timer('false');//останавливает таймер ... код//выполняет нужный мне код timer();//опять запускается таймер } 

Does not work and does not stop. Removed the timer(); в $("#cimg2").click(function(event) timer(); в $("#cimg2").click(function(event) to check if it stops the timer, it didn’t stop. I can’t understand why in this case it doesn’t stop the timer, and how to make it work.

  • one
    @harley, To format a code, select it with the mouse and click on the {} button of the editor. ______ Type var intervalId; before function timer () {} but do not write var inside the function var. Only it is not clear why you need this, if you have a synchronous code on click, then the interval will not work while your code is being executed. - zb '

1 answer 1

setTimeout, setInterval can be canceled with the clearTimeout and clearInterval functions:

 var idIntervals=0; function timer(){ //to do something. } $("#cimg2").click(function(event){ clearInterval(idIntervals);//тут останавливаем таймер idIntervals=setInterval(function(){timer();},1000);//опять запускается таймер }