F
F
ff0xff2020-01-31 12:39:30
Layout
ff0xff, 2020-01-31 12:39:30

How to execute a function every n seconds for x seconds?

There is a function that runs the code every n seconds:

setInterval(function()
{
//некоторые действия функции
},20000);

As if everything is ok, but I need it to stop after x seconds... how to do it?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
Vitaly Kuznetsov, 2019-05-09
@vitaly44

You can try setting the line-height

A
Alexander, 2020-01-31
@ff0xff

let timer = setInterval(callback, 20000);
setTimeout(clearInterval, 15 * 60 * 1000, timer); // setInterval остановится через 15 минут

B
BATPYIIIKOB, 2020-01-31
@BATPYIIIKOB

Set a counter variable that will record the total elapsed time :). Then turn off the counter :)
https://learn.javascript.ru/settimeout-setinterval
Here is an example of calculating the delay:

let start = Date.now();
let times = [];

setTimeout(function run() {
  times.push(Date.now() - start); // запоминаем задержку от предыдущего вызова

  if (start + 100 < Date.now()) alert(times); // показываем задержку через 100 мс
  else setTimeout(run); // если нужно ещё запланировать
});

just twist it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question