Home > OS >  Not able to access variable inside setInterval in javaScript
Not able to access variable inside setInterval in javaScript

Time:06-22

I want to print the word according to 15s timer and then afterwards I want to change that word.

For that I have take an array of words and then take a random number generator to pick up the random word from the array using random number as array index value.

And for timer I have use setInterval as time function but when I call the array i.e. words and try to print it on screen I m getting undefined as the result i.e. I m not able to access the array i.e. words inside my setInterval function

function startTimer(duration, display) {
  var wordCount = 0;
  var wordNo = Math.floor((Math.random() * (59 - wordCount))   1);
  wordCount  = 1;
  word.innerHTML = "<b>"   wordCount   ". "   words[wordNo]   "</b>";
  words = words - words[wordNo];
  var timer = duration,
    minutes, seconds;
  setInterval(function() {
    seconds = parseInt(timer % 60, 10);
    seconds = seconds < 10 ? "0"   seconds : seconds;
    display.textContent = seconds;

    if (--timer < 0) {
      timer = duration;
    }
    if (seconds == 5) {
      display.style.color = 'red';
    }
    if (seconds > 5) {
      display.style.color = 'unset';
    }

    if (seconds == 00) {
      wordNo = Math.floor((Math.random() * (59 - wordCount))   1);
      wordCount  = 1;
      word.innerHTML = "<b>"   wordCount   " . "   words[wordNo]   "</b>";
      words = words - words[wordNo];

    }

    if (wordCount == 61) {
      let wrapper = document.querySelector('.wrapper');
      wrapper.innerHTML = "<div class='text-center fs-3 mt-3 text-danger'>Test Ended</div>"
    }
  }, 1000);


}

var words = ["Scene", "Impossible", "Society", "Choose", "Unjust", "Image", "Exam", "Drive", "Internet", "Communication", "Keys", "Murder", "Commit", "Flee", "Practice", "Organize", "Phone", "New", "Agency", "Security", "Since", "Peace", "Fall", "Hi", "Run", "Chase", "Enter", "Industry", "Limit", "Development", "Coach", "Food", "Special", "Biomass", "Release", "Head", "Launch", "Medal", "Play", "Department", "Under", "Curb", "Cooperate", "HIke", "War", "Normal", "Challenge", "Serving", "Bane", "Rapid", "Actress", "obstacles", "Strict", "Forceful", "Citizens", "Team", "Anxious", "Knowledge", "Polite", "Integrity", "Serve", "Loyal", "Equality", "Justice", "Gratitude", "Rare", "Heavy", "Rude", "Explanation", "Pilot", "Pirate", "Ship", "Captain", "Camp", "Rights", "Ragging", "Rust", "Patriotism", "Primary", "Performance", "Pity", "Meeting", "Obedience", "Quick", "Quiet", "Quotes", "Question", "Try", "Unity", "Urge", "Friendship", "Close", "Migrate", "Decline", "Fly", "Highest", "Shall"]
var display = document.querySelector('#time');
var word = document.querySelector('#word');
var fiveMinutes = 15;
message = "1.60 words would be shown one by one.\r\n2.Each word will appear for only 15 seconds.\r\n3.The candidate has to read the word and write appropriate sentences at the same time.\r\n4.There will be no gap between two simultaneous words.\r\n5.The words can be positive or negative.\r\n6.The duration of WAT is 15 minutes."
alert(message)
startTimer(fiveMinutes, display);
<script src="https://kit.fontawesome.com/bf341fb126.js" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<div >

  <header >
    Word Association Test
  </header>
  <div >
    <i  aria-hidden="true"></i>
  </div>

  <div id="time" ></div>

  <div id="word" >



  </div>

</div>
<script src="JavaScript/script.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-7 zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG 2QOK9T ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>

CodePudding user response:

You need to shuffle your code around to have global vars outside the function

Also DRY, do not repeat yourself

Lastly use the length of the array as count

I use splice to remove the word from the array

var words = ["Scene", "Impossible", "Society", "Choose", "Unjust", "Image", "Exam", "Drive", "Internet", "Communication", "Keys", "Murder", "Commit", "Flee", "Practice", "Organize", "Phone", "New", "Agency", "Security", "Since", "Peace", "Fall", "Hi", "Run", "Chase", "Enter", "Industry", "Limit", "Development", "Coach", "Food", "Special", "Biomass", "Release", "Head", "Launch", "Medal", "Play", "Department", "Under", "Curb", "Cooperate", "HIke", "War", "Normal", "Challenge", "Serving", "Bane", "Rapid", "Actress", "obstacles", "Strict", "Forceful", "Citizens", "Team", "Anxious", "Knowledge", "Polite", "Integrity", "Serve", "Loyal", "Equality", "Justice", "Gratitude", "Rare", "Heavy", "Rude", "Explanation", "Pilot", "Pirate", "Ship", "Captain", "Camp", "Rights", "Ragging", "Rust", "Patriotism", "Primary", "Performance", "Pity", "Meeting", "Obedience", "Quick", "Quiet", "Quotes", "Question", "Try", "Unity", "Urge", "Friendship", "Close", "Migrate", "Decline", "Fly", "Highest", "Shall"]
var display = document.querySelector('#time');
var word = document.querySelector('#word');
var fiveMinutes = 15;
message = "1.60 words would be shown one by one.\r\n2.Each word will appear for only 15 seconds.\r\n3.The candidate has to read the word and write appropriate sentences at the same time.\r\n4.There will be no gap between two simultaneous words.\r\n5.The words can be positive or negative.\r\n6.The duration of WAT is 15 minutes."
let wordCount = 0
const getWord = () => {
  var len = words.length;
  var wordNo = Math.floor(Math.random() * wordCount);
  wordCount  = 1;
  word.innerHTML = "<b>"   wordCount   ". "   words[wordNo]   "</b>";
  words.splice(wordNo, 1);
};
let tId;
const wrapper = document.querySelector('.wrapper');
alert(message)
getWord()
startTimer(fiveMinutes, display);


function startTimer(duration, display) {
  var timer = duration,
    minutes, seconds;
  tId = setInterval(function() {
    if (words.length === 0) {
      wrapper.innerHTML = "<div class='text-center fs-3 mt-3 text-danger'>Test Ended</div>"
      clearInterval(tId);
      return
    }

    seconds = parseInt(timer % 60, 10);
    seconds = seconds < 10 ? "0"   seconds : seconds;
    display.textContent = seconds;

    if (--timer < 0) {
      timer = duration;
    }
    if (seconds == 5) {
      display.style.color = 'red';
    }
    if (seconds > 5) {
      display.style.color = 'unset';
    }

    if (seconds == 00) {
      getWord()
    }

  }, 1000);


}
<script src="https://kit.fontawesome.com/bf341fb126.js" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<div >

  <header >
    Word Association Test
  </header>
  <div >
    <i  aria-hidden="true"></i>
  </div>

  <div id="time" ></div>

  <div id="word" >



  </div>

</div>
<script src="JavaScript/script.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-7 zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG 2QOK9T ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>

  • Related