Javascript message loop
I have 3 messages in variables.
var msg1 = "hello1";
var msg2 = "hello2";
var msg3 = "hello3";
I am trying to create a function that when I click on it the first time I run console.log (msg1), when I click on it the second time it is console.log (msg2) the third time is console.log (msg3) the 4th time console.log (msg1) and 5th msg2 etc.
$scope.clickMsg = function () {
console.log(msg1);
}
I've tried loops, timers, etc., but I couldn't get it to work.
Does anyone know how to do this?
source to share
Use an array instead and it's a little easier, you just increment the number on every click and use that number to select an item from the array
var msg = [
"hello1",
"hello2",
"hello3"
];
var i = 0;
var $scope = {};
$scope.clickMsg = function () {
console.log( msg[i] );
i++; // increment
if (i === msg.length) i = 0; // reset when end is reached
}
document.getElementById('test').addEventListener('click', $scope.clickMsg)
<button id="test">Click</button>
source to share
ES6 Version Based Generators :
var messages = (function*() {
for(;;) { yield msg1; yield msg2; yield msg3; }
})()
$scope.clickMsg = function () {
console.log(messages.next().value);
}
Unlike the other answers, you are not required to use a different datatype and will also work for locally scoped variables (i.e. variables not bound to a window).
source to share
There are several ways to do this in terms of string access, I would recommend putting them in an array rather than referring to the global / scoped object, but that is up to you. Anyway for the code.
var messagesArray = ["hello1", "hello2", "hello3"];
var messagesObject = {
msg1: "hello1",
msg2: "hello2",
msg3: "hello3"
}
var counter = 0;
function LogMessage() {
console.log(messagesArray[counter % 3]);
console.log(messagesObject["msg" + (counter % 3 + 1)]);
counter++
}
<button onclick="LogMessage()">Click Me</button>
source to share
Just use with this increment value
var msg1 = "hello1";
var msg2 = "hello2";
var msg3 = "hello3";
var c = 1;
$scope.clickMsg = function () {
c = c > 3 ? 1 : c;
console.log(window['msg'+c])
c++;
}
Working snippet
var msg1 = "hello1";
var msg2 = "hello2";
var msg3 = "hello3";
var c = 1;
var $scope={} //for testing
$scope.clickMsg = function () {
c = c > 3 ? 1 : c;
console.log(window['msg'+c])
c++;
}
function check(){ //for testing
$scope.clickMsg();
}
<button onclick="check()">click</button>
source to share
just do something like this, will work for you, make sure you reset it back if necessary, or do something else after the first loop you get undefined:
var msgs = ["hello1","hello2","hello3"], i=0;
$scope.clickMsg = function() { //angular $scope for example
console.log(msgs[i]);
if(i < msgs.length-1) {
i++;
} else {
i=0; //reset the loop
}
}
source to share