user2994073
user2994073

Reputation: 3

Timer which runs loops

Question has been answered.

Note: Im trying to output this to a webpage i only used console for reference. I have the css code set up.

    var r_text = ['Hi', 'Go', 'No'];
function countdown() {

    var count = 20;
    var timerId = setInterval(function() {
        count--;
        console.log(count);

        if(count == 0) {
            console.log(r_text[Math.floor( Math.random() * r_text.length )]);
            count = 20;
        }
    }, 1000);
}
countdown();

Upvotes: 0

Views: 141

Answers (1)

Fabrício Matté
Fabrício Matté

Reputation: 70209

var r_text = ['Hi', 'Go', 'No'],
    textProp = 'textContent' in document.createElement('div') ?
               'textContent' :
               'innerText',
    //update this ID selector to match an element in the page:
    elementToReceiveWord = document.getElementById('WORD'),
    seconds = 20; //timer in seconds

function countdown() {
    var count = seconds;
    var timerId = setInterval(function() {
        count--;
        console.log(count);

        if(count == 0) {
            var word = r_text[Math.floor( Math.random() * r_text.length )];
            elementToReceiveWord[textProp] = word;
            setTimeout(function() {
                  elementToReceiveWord[textProp] = '';
            }, 5000);
            count = seconds;
        }
    }, 1000);
}
countdown();

Demo

Don't forget to update the elementToReceiveWord's ID selector to select an element in the page.

There were a couple mistakes with your original code:

  • r_randomtext/r_text var name mismatches;
  • Not drawing a new random value before showing the texts;
  • Wrong length of the array in Math.random() * x;
  • Timer was 10s instead of the requested 20s.

Improvements:

  • Use literal array syntax (more concise, shorter and interpreter optimization-friendly).
  • Inline'd some Math operations.

I've employed a feature detection check for elements' text property as well. All modern browsers support textContent which is the W3C standard, I'm using innerText as a fallback for old IE. Chrome supports both properties, Firefox only supports textContent, and IE<9 does not support textContent (hence the innerText fallback).

If you don't care about old IE, you can remove that check and simply use element.textContent = ... instead.

Upvotes: 1

Related Questions