Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140762

How to pick an item from an array and keep on cycling through by using Javascript?

$
0
0

I actually want to pick an item from the array (A or B or C) and display it in a block. Then changes at 2 second interval and keep on cycling through.

<script type="text/javascript">
        var arr = ["A","B","C"];
        setInterval(function ChangeText() {
            var span = document.getElementById("spnChanger")
            var i = Math.floor(Math.random() * 3)
            span.innerHTML = arr[i]
        }, 2000);
</script>
  • Such as if A is randomly picked, A will be shown at first, followed by B and C and then back to A and loop endlessly

  • Such as if B is randomly picked, B will be shown at first, followed by C and A and then back to B and loop endlessly

  • Such as if C is randomly picked, C will be shown at first, followed by A and B and then back to C and loop endlessly

But all i can get is a random item from the array every time which cannot continuously go through the cycle.

Can anyone help? Thanks


Viewing all articles
Browse latest Browse all 140762

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>