@Ucorp

Проблема с setTimeout, как исправить?

Есть код:
function one() {
setTimeout(one,  10000)
  console.log('one')
  two()
}

function two() {
  setTimeout(two,  2000)
  console.log('two')
}

one()


При срабатывании таймаута функции one, таймаут функции two начинает срабатывать чаще чем надо. Тоже самое и с one.
  • Вопрос задан
  • 217 просмотров
Решения вопроса 1
@Ucorp Автор вопроса
Решил так:
function getCode() {
    reqwest({
        url: '/code.json',
        method: 'get',
        data: {
            client_id: 'wer',
            client_secret: 'asdfghjk,mnbvcxsdfghj'
        },
        error: function (error) {
            console.log(error)
        },
        success: function(response) {
            console.log(response);
            localStorage.code = response.code;
            localStorage.interval = response.interval;

            getToken();

            setTimeout(function() {
                var id = window.setTimeout(function() {}, 0);

                while (id--) {
                    window.clearTimeout(id);
                }

                getCode();
            }, response.expires_in * 1000);
        }
    })
}

function getToken() {
    reqwest({
        url: '/token.json',
        method: 'get',
        data: {
            client_id: 'wer',
            client_secret: 'asdfghjk,mnbvcxsdfghj',
            code: localStorage.code
        },
        error: function (error) {
            console.log(error)
            setTimeout(getToken, localStorage.interval * 1000);
        },
        success: function(response) {
            console.log(response);
        }
    })
}
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
mlnkv
@mlnkv
JavaScript Developer
function getCode(url) {
  $.get(url, function(response) {
    if (resonse.ok) {

      /* is ok, do something */

      setTimeout(function() { getCode('first_url') }, 20 * 1000)
    } else {
      /* is no ok, repeat after 5 sec */
      setTimeout(function() { getCode('second_url') }, 2 * 1000)
    }
  })
}
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы