ArthurH
ArthurH

Reputation: 293

Why isn't setInterval() returning my function's return value?

I'm very new to coding (2 weeks experience) so please bare with my silly question about this code. Ultimately I want it to continuously run the function called "timer," which tells me how long it took to run the function called "add," display that result on my screen, and then update that results each time it runs.

function add(a,b){ 
  return a + b;
}

function timer(){
  var a = Math.floor(Math.random() * 101);
  var b = Math.floor(Math.random() * 101);
  var start = performance.now();
  add();
  var end = performance.now();
  var duration = end - start;
  return duration + ' milliseconds';
}

t = setInterval(timer,1000);

What this seems to do is return the number "1" and do nothing after.

Now when I replace

return duration + ' milliseconds' 

with

console.log(duration + ' milliseconds') 

it does what I want, except for the fact that the reason I don't want to use console.log is that it jumps to a new line when displaying the duration instead of replacing the previous line with the new duration. To clarify, I don't want a big list of durations that gets longer every time it runs, I just one one duration displayed, that gets updated and replaced each time it runs.

Thank you for your help!

Upvotes: 1

Views: 4703

Answers (5)

nbarbosa
nbarbosa

Reputation: 1712

When you say

display that result on my screen

I'm thinking you may be just looking to update an element's text. If you simply want to keep track of it, you will need to use a variable outside of the timer function and update that variable inside the function. As others have pointed, setInterval will return an ID for retrieving the interval later. For example, if you wanted to stop the timer, you would do clearInterval(t);

I created a code snippet that updates the duration on the screen every time:

function add(a,b){ 
  return a + b;
}

function timer(){
  var a = Math.floor(Math.random() * 101);
  var b = Math.floor(Math.random() * 101);
  var start = performance.now();
  add();
  var end = performance.now();
  var duration = end - start;
  document.getElementById('duration').innerHTML = duration + ' milliseconds';
}

t = setInterval(timer,1000);
Duration: <span id="duration"></span>

Also, take a look at this, since you are new to coding: How do I return the response from an asynchronous call?

Upvotes: 0

Intervalia
Intervalia

Reputation: 10945

If you want to be notified when setInterval is finished then you may need to use a promise:

function add(a,b) { 
  return a + b;
}

function timer(delayTime) {
  return new Promise(
    function(resolve) {
      setInterval(
        function() {
          var a = Math.floor(Math.random() * 101);
          var b = Math.floor(Math.random() * 101);
          var start = performance.now();
          add();
          var end = performance.now();
          var duration = end - start;
          resolve(duration + ' milliseconds');
        }, delayTime
      );
    }
  );
}

timer(1000).then(
  function(t) {
    console.log(t);
  }
);

Upvotes: 0

Faizal Shap
Faizal Shap

Reputation: 1820

The function console.log appends to the console. So you will have to clear the console to achieve what you want.

If you are on chrome then call the

clear() 

before console.log() in timer function.

Hope it helps

Upvotes: 0

efong5
efong5

Reputation: 526

You are setting t to the return value of setInterval()

The documentation says that setInterval() returns the following:

timeoutID ... a numeric, non-zero value which identifies the timer

It seems like what you actually want is to set the variable t somewhere inside timer(), so that when setInterval() calls it every 1000ms, it'll update t.

Upvotes: 1

Deryck
Deryck

Reputation: 7658

setInterval is asynchronous so you will not get your return value this way. The number you are getting back is an ID for later when you want to clearInterval.

But let's say for fun setInterval did try to return your value.

You do t = setInterval(...) but when that happens your code inside of setInterval hasn't executed yet. It was just placed in the queue at that moment but the assignment of t = ... isn't waiting around.

maybe this could help https://code.tutsplus.com/tutorials/event-based-programming-what-async-has-over-sync--net-30027

Upvotes: 4

Related Questions