user14331096
user14331096

Reputation:

Run code with a different outcome every 30 seconds

I have 2 variables called var1, and var2:

var var1 = 'foo';
var var2 = 'bar';

I'd like to be able to log one of these variables to the console every 30 seconds, with the variables alternating being logged (here's some pseudo-code):

Log var1 to console

Wait 30 seconds

Log var2 to console

Wait 30 seconds

Repeat

Any way to do this? I believe I should be doing something related with setInterval, but my solution:

setInterval(function() {
    console.log(var1);
    setTimeout(() => {
        console.log(var2);
    }, 30000);
}, 60000);

Doesn't seem to be the best solution. Is there a more efficient way to do this?

Upvotes: 1

Views: 58

Answers (4)

gillyspy
gillyspy

Reputation: 1598

You want to use setInterval so that the interval is consistent and there is no execution time involved in establishing the time for the next async call.

You can pass in an object reference to control scope and also track the boolean and flip it:

 setInterval(function(a){
        a.bool = !a.bool
        if(!a.bool){
            console.log( a.var1)
            return
         } 
         console.log(a.var2)
    }, 3000, {
    bool : true,
    var1 : 'value', 
    var2 : 'other value'
    })

Upvotes: 1

Reuven Chacha
Reuven Chacha

Reputation: 889

Here's a more generic approach: For a given list of values - it'll print the provided values in a cycle forever, and will wait for intervalMs between every print

/**
 * 
 * @param {Array} values - collection of values to log
 * @param {Number} intervalMs - the log interval
 */
function logValuesCyclicForever(values, intervalMs = 30000) {
  let index = 0;
  return setInterval(() => {
    console.log(values[index]);
    index = (index + 1) % values.length; // sets the location back to 0 when the last element is printed.
  }, intervalMs);
}

var var1 = 'foo';
var var2 = 'bar';

logValuesCyclicForever([var1, var2]); // for your use case

Upvotes: 0

SpoonMeiser
SpoonMeiser

Reputation: 20467

You could use setTimeout with two functions that call each other:

var var1 = 'foo';
var var2 = 'bar';

const log1 = () => {
  console.log(var1);
  setTimeout(log2, 30000)
}

const log2 = () => {
  console.log(var2);
  setTimeout(log1, 30000)
}

log1();

Upvotes: 0

Marc
Marc

Reputation: 11633

Just keep counter that enables you to alternate.

var counter = 0;
var var1 = "ONE!";
var var2 = "TWO!";
var frequency = 1000; //1000 is for illustration for the example

setInterval(function() {
   if( counter++ % 2 == 0 ) {
     console.log(var1);
   } else {
     console.log(var2);
   }
}, frequency );

Upvotes: 1

Related Questions