There is a function that runs every 5 seconds. How to make it so that when you click on the button, the interval is restarted first.

Example: every 5 seconds an alert () is displayed. But as soon as we press a button (for example, at 4 seconds), then we again wait for 5 seconds before a new alert.

An example of an alert output function:

var f = function() { alert("Привет") setTimeout(arguments.callee, 5000); } setTimeout(f, 5000); 

  • no, timers are disposable, if you stop it, then only create a new one - Grundy
  • @Grundy, is it only necessary to use setInterval ? - Mr. Black
  • @Doofy, same timer interval: the same timer can not be stopped, and then started, you can only create a new one - Grundy
  • one
    arguments.callee better not to use, it is better to give the name of the function and call it by name - Grundy

1 answer 1

 function f() { console.log('выполнено'); } document.querySelector('button').onclick = function() { timer.start(3000); }; timer = { start: function(time) { if(typeof(t) == 'undefined') { console.log('старт'); } else { console.log('заново'); clearTimeout(t); } t = setTimeout(function() {f();}, time); } } 
 <button>Запуск</button>