I am trying to make a program that randomly displays one of four defined emojis given in an array when the button is clicked and switches every two seconds continues to do so until the stop button is clicked. Note that I have not finished the stop function yet as I cannot work out why my randomEmoji function is not displaying anything. Thanks in advance :).
var display = document.getElementById("emojiDisplay");
var emojiList = ["š„³", "š¤©", "š¾", "šµ"];
function randomEmoji() {
emojiDisplay.innerHTML = emojiList[Math.floor(Math.random() *
emojiList.length)];
setInterval(function() {
document.getElementById("emojiDiplay").innerHTML = emojiList[i++];
if (i == emojiList.length) i = 0;
}, 2000);
}
function stop() {
}
<button onclick=randomEmoji()>Display random emoji</button>
<button onclick=stop()>Stop</button>
</br>
</br>
<div id="emojiDisplay">
</div>
Based on your idea and your code, Iāve updated it and let it work (the stop function works, too). You can check the below demo:
var display = document.getElementById("emojiDisplay");
var emojiList = [ "š„³", "š¤©", "š¾", "šµ" ];
var i = 0;
var timer;
function randomEmoji() {
clearInterval(timer);
// Call show Emoji to let it shows instanly.
showEmoji();
// Put showEmoji function to let it repeats
timer = setInterval(function() {
showEmoji();
}, 2000);
}
function showEmoji() {
i = Math.floor(Math.random() * emojiList.length);
emojiDisplay.innerHTML = emojiList[i];
}
function stop() {
// clear interval timer to let it stops
clearInterval(timer);
}
<!DOCTYPE html>
<html>
<head>
<title>EmojiRandomiser</title>
</head>
<body>
<button onclick=randomEmoji()>Display random emoji</button>
<button onclick=stop()>Stop</button>
<br>
<br>
<div id="emojiDisplay">
</div>
</body>
</html>