Получайте новое значение каждые n секунд - PullRequest
0 голосов
/ 02 апреля 2019

У меня есть веб-страница, где я показываю цитату. Я выбираю одну из цитат наугад. В настоящее время он делает это каждый раз, когда веб-страница загружается, я бы предпочел, чтобы она выбиралась по одному каждые 5 секунд. Я новичок и не уверен, как лучше реализовать ни эту, ни соответствующую функцию. setInterval ?, setTimeout ?, delay ?, wait?

var quotes = JSON.parse('{\
    "0": "Don\'t worry about what anybody else is going to do. The best way to predict the future is to invent it. -- Alan Kay", \
    "1": "Keep away from people who try to belittle your ambitions. Small people always do that, but the really great make you feel that you, too, can become great. -- Mark Twain", \
    "2": "No problem should ever have to be solved twice. -- Eric S. Raymond, How to become a hacker", \
    "3": "Attitude is no substitute for competence. -- Eric S. Raymond, How to become a hacker", \
    "4": "It is said that the real winner is the one who lives in today but able to see tomorrow. -- Juan Meng", \
    "5": "Fools ignore complexity. Pragmatists suffer it. Some can avoid it. Geniuses remove it. -- Alan J.Perlis(Epigrams in programming)", \
    "6": "A year spent in artificial intelligence is enough to make one believe in God. -- Alan J.Perlis(Epigrams in programming)" \
}');

function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}
var num = Math.floor(getRandomArbitrary(0, Object.keys(quotes).length));

document.getElementById('quote').innerHTML = quotes[num];

Как уже упоминалось, я бы хотел, чтобы значение в идентификаторе 'quote' обновлялось каждые 5 секунд. Так что я бы предположил, что это означает обновление num var?

Ответы [ 3 ]

1 голос
/ 02 апреля 2019

Вы действительно можете использовать setInterval для достижения этой цели. Попробуйте добавить setInterval следующим образом:

var quotes = JSON.parse(
      '{\
      "0": "Don\'t worry about what anybody else is going to do. The best way to predict the future is to invent it. -- Alan Kay", \
      "1": "Keep away from people who try to belittle your ambitions. Small people always do that, but the really great make you feel that you, too, can become great. -- Mark Twain", \
      "2": "No problem should ever have to be solved twice. -- Eric S. Raymond, How to become a hacker", \
      "3": "Attitude is no substitute for competence. -- Eric S. Raymond, How to become a hacker", \
      "4": "It is said that the real winner is the one who lives in today but able to see tomorrow. -- Juan Meng", \
      "5": "Fools ignore complexity. Pragmatists suffer it. Some can avoid it. Geniuses remove it. -- Alan J.Perlis(Epigrams in programming)", \
      "6": "A year spent in artificial intelligence is enough to make one believe in God. -- Alan J.Perlis(Epigrams in programming)" \
    }'
    );
    
    function getRandomArbitrary(min, max) {
      return Math.random() * (max - min) + min;
    }
    
    function updateQuote() {
      var num = Math.floor(getRandomArbitrary(0, Object.keys(quotes).length));
      document.getElementById("quote").innerHTML = quotes[num];
    }
    
    updateQuote();
    setInterval(updateQuote, 5000);
<h3 id="quote"></h3>

Второй параметр setInterval принимает число миллисекунд, поэтому в вашем случае это 5000. Подробнее здесь

0 голосов
/ 02 апреля 2019

@ shmink, хорошо, что вы придумали код для заполнения div, я добавил фрагмент для вызова этого в setInterval, который обновляется каждые 5 секунд.Убедитесь, что вы вызываете clearInterval, чтобы остановить setInterval, когда вы уходите (переместитесь на другую страницу, закройте).

var quotes = JSON.parse('{\
    "0": "Don\'t worry about what anybody else is going to do. The best way to predict the future is to invent it. -- Alan Kay", \
    "1": "Keep away from people who try to belittle your ambitions. Small people always do that, but the really great make you feel that you, too, can become great. -- Mark Twain", \
    "2": "No problem should ever have to be solved twice. -- Eric S. Raymond, How to become a hacker", \
    "3": "Attitude is no substitute for competence. -- Eric S. Raymond, How to become a hacker", \
    "4": "It is said that the real winner is the one who lives in today but able to see tomorrow. -- Juan Meng", \
    "5": "Fools ignore complexity. Pragmatists suffer it. Some can avoid it. Geniuses remove it. -- Alan J.Perlis(Epigrams in programming)", \
    "6": "A year spent in artificial intelligence is enough to make one believe in God. -- Alan J.Perlis(Epigrams in programming)" \
}');

function updateUI() {
var num = Math.floor(getRandomArbitrary(0, Object.keys(quotes).length));

document.getElementById('quote').innerHTML = quotes[num];
}

function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}

var interval = setInterval(updateUI, 5000);

//cleanup
//clearInterval(interval);
<div id="quote"></div>
0 голосов
/ 02 апреля 2019

Вы можете использовать setInterval , который многократно вызывает функцию или выполняет фрагмент кода, с фиксированной задержкой по времени и внутри функции обратного вызова каждый раз получает новый num.

var quotes = JSON.parse('{\
    "0": "Don\'t worry about what anybody else is going to do. The best way to predict the future is to invent it. -- Alan Kay", \
    "1": "Keep away from people who try to belittle your ambitions. Small people always do that, but the really great make you feel that you, too, can become great. -- Mark Twain", \
    "2": "No problem should ever have to be solved twice. -- Eric S. Raymond, How to become a hacker", \
    "3": "Attitude is no substitute for competence. -- Eric S. Raymond, How to become a hacker", \
    "4": "It is said that the real winner is the one who lives in today but able to see tomorrow. -- Juan Meng", \
    "5": "Fools ignore complexity. Pragmatists suffer it. Some can avoid it. Geniuses remove it. -- Alan J.Perlis(Epigrams in programming)", \
    "6": "A year spent in artificial intelligence is enough to make one believe in God. -- Alan J.Perlis(Epigrams in programming)" \
}');

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}
// you need this value only once so no need to get it at every interval
let maxVal =Object.keys(quotes).length);
setInterval(() => {
  var num = Math.floor(getRandomArbitrary(0,maxVal);
  document.getElementById('quote').innerHTML = quotes[num];
}, 5000)
<div id='quote'></div>
...