WoJ
WoJ

Reputation: 29987

Does setInterval() require different function names?

When learning Vue, I created two timers updating component data. When copy/pasting, I did not change, by mistake, the name of the second function in setInterval() but the code runs correctly nevertheless (the Vue part is not relevant, I keep it to have a functioning example but the core of my question is about the timers at the bottom of the code):

var data_mynumber = {
  time: 1
};

Vue.component('mynumber', {
  template: '<div>time is {{time}}</div>',
  data: function() {
    return data_mynumber;
  }
})

var data_smthg = {
  time: 5
};

Vue.component('smthg', {
  template: '<div>hello {{time}}</div>',
  data: function() {
    return data_smthg;
  }
})


var vm = new Vue({
  el: '#root'
})

setInterval(
  function myTimer() {
    var d = new Date();
    data_mynumber.time = d.toLocaleTimeString();
  },
  1000
);

setInterval(
  function myTimer() {
    var d = new Date();
    data_smthg.time = d;
  },
  100
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.5/vue.js"></script>
<div id="root">
  <mynumber></mynumber>
  <smthg></smthg>
</div>

Both setInterval() call the same function name myTimer(), each of them being different. The code runs as expected: the timers have a different tempo.

Is this working by chance or can I reuse the same function name across all my setInterval() calls?

Upvotes: 1

Views: 229

Answers (2)

R&#244;mulo M. Farias
R&#244;mulo M. Farias

Reputation: 1523

As matter of fact you don't need the name of the function. It's called anonymous functions or lambdas and doesn't make difference the name. You are passing it as a parameter, a callback. It won't call the name of the function, it will call the reference.

In the case of your code this would be

setInterval(
  function() {
    var d = new Date();
    data_mynumber.time = d.toLocaleTimeString();
  },
  1000
);

Upvotes: 2

AJ X.
AJ X.

Reputation: 2770

The function names have different scopes and therefore will not collide.

Although -- for debugging, it might be helpful to use different names.

Upvotes: 4

Related Questions