Reading the code in the tutorial I did not understand the logic of this excerpt:

Asked

Viewed 74 times

2

I was seeing a tutorial on an accountant on the website of devFuria and it presents the code commented below.

    var btnStart = document.getElementById('btn-start');
    var btnStop  = document.getElementById('btn-stop');
    var display  = document.getElementById('display');
    var id       = null;

    btnStart.onclick = function() {
      // A animação não será reiniciada caso (comentário do tutorial)
     // já tenha sido iniciada (comentário do tutorial)


    //Minha dúvida está nesse trecho
    if(!id) {
    // A mágica... (comentário do tutorial)
    id = setInterval(function () {
      display.value = Number(display.value) + 1;
    }, 100);    
  }
}

    btnStop.onclick = function() {
      // Desliga a animação mas
      // o valor de `id` continua sendo válido (true) (comentário do tutorial)
      clearInterval(id);
      // Anulamos o valor da variável id,
      // é como se ela fosse uma variável de controle (comentário do tutorial)
      id = null;
    }

In the code section where you have the (!id), he says that this is where it will prevent the counter to restart the count if it has already been started. I don’t understand the logic of create an id = null variable and use, in if, the (!id) to start the countdown. And why do I have to set null in id when using clearInterval at the end?

2 answers

2

First of all for you to understand the flow of a log console in id and see what it returns in the function is passing a ! id this symbol ! and referenced by negation then it would be if it does not have an id = ! id console.log(id) Concerning:

 if(!id) {
    // A mágica... (comentário do tutorial)
    id = setInterval(function () {
      display.value = Number(display.value) + 1;
    }, 100);    
  }

Concerning :

  clearInterval(id);
  // Anulamos o valor da variável id,
  // é como se ela fosse uma variável de controle (comentário do tutorial)
  id = null;

it is necessary to create the id variable because in clearInterval you are calling an id clearInterval(id);

if you do not declare the id to be null, the console will curse you for not having declassified the variable I need so that I can consume a variable in my function it has to be declared so if you pass an id=null, or id=0 will in it’s starting at 0 or null, remember always if I am consuming a variable it has to be stated.

  • 1

    Good morning, Victor, thanks for your help. I was looking at other responses in stackoverflow about null and Undefined in Javascript and read the following explanation: "null and Undefined are falsey values, that is, they are converted to false when forced to boolean." So I think if (!id) is waiting for a true result - so the exclamation -, since by default it is falsey, it returns false. As for id = null in clearInterval, I understand your explanation, thank you. But I’m still trying to understand the rest of the rsrsrs code.

1


I imagine that, essentially, your doubt lies in a specific concept of javascript: true and false values. The most commonly used terms to define them are Truthy and falsy, in English.

It is important to understand the difference between boolean values true and false and true and false values:

Any true value will be considered true when using under false conditions and values shall be considered false. This MDN documentation can help you understand about false values.

Any of the following values is false:

  • false
  • null
  • undefined
  • 0
  • "" (empty string)
  • NaN (Not a number)

This means that while id for null the condition !id is true, since the negation of a false value is true.

The function setInterval returns an integer (not zero). Any nonzero integer is a true value. That is, so id = setInterval(...); is executed, the condition !id is false. And this ensures that the counter will be started only before setInterval have been called for the first time.

But, why the excerpt id = null is necessary after clearInterval(id)? The function clearInterval does not change the value of id, therefore, this variable continues with the nonzero integer value (i.e., a true value). To allow the code within the if(!id) run again, we need to give a false value to id (in this case, null).

I believe that some small changes facilitate the understanding of the counter’s behavior:

var btnStart  = document.getElementById('btn-start');
var btnStop   = document.getElementById('btn-stop');
var display   = document.getElementById('display');
var id        = null;
var isRunning = false;

btnStart.onclick = function() {
  // A animação não será reiniciada caso (comentário do tutorial)
  // já tenha sido iniciada (comentário do tutorial)


  //Minha dúvida está nesse trecho
  if(!isRunning) {
    // A mágica... (comentário do tutorial)
    id = setInterval(function () {
      display.value = Number(display.value) + 1;
    }, 100);
    isRunning = true; // A animação continuara ate isRunning receber false
  }
}

btnStop.onclick = function() {
  // Desliga a animação mas
  // o valor de `id` continua sendo válido (true) (comentário do tutorial)
  clearInterval(id);
  // Anulamos o valor da variável id,
  // é como se ela fosse uma variável de controle (comentário do tutorial)
  isRunning = false; // A animação ficara parada ate isRunning receber true
}

A final comment: what Victor commented about the variable needs to be started (or the console will complain), actually occurs. This is a precaution coming from the history of computing. When a variable is declared, a computer memory space is reserved for this variable, but this space was not always empty before it was used. Some languages (such as C, for example) do not "clear" this space before giving it to the variable, so the initial value of a variable can be unpredictable if it is not explicitly determined. To avoid problems arising from unexpected initial values in variables has become a good practice of programming always give initial values (Zero is a common value for numerical variables, for example).

In the case of javascript, more specifically, this console warning occurs to hinder access to undefined variables (undefined), since this type of access causes errors.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.