-4

There is a counter made as an example in w3c schools website right here http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_settimeout_cleartimeout2

var c = 0;
var t;
var timer_is_on = 0;

function timedCount() {
    document.getElementById("txt").value = c;
    c = c + 1;
    t = setTimeout(function(){timedCount()}, 1000);
}

function startCount() {
    if (!timer_is_on) {
        timer_is_on = 1;
        timedCount();
    }
}

function stopCount() {
    clearTimeout(t);
    timer_is_on = 0;
}

I don't understand the startCount function. I don't understand for what purposes it is written and I can't translate it into 'human' language, so I could understand it.

An if statement runs if it is true, right ? It checks if !timer_is_on is true and than executes the code. But what does (!timer_is_on) mean ? Is zero converted to false and then the ! converts it to true ? Or does it say if 'not 0' than... But than it won't execute because there is no else{} and var timer_is_on is always = 0.

Tomas.R
  • 715
  • 2
  • 7
  • 18

3 Answers3

2

The 0 is converted to false before ! logically negates it, producing true.

user2357112
  • 260,549
  • 28
  • 431
  • 505
1

if(x) means "if x is true"

if(!x) means "if not x is true", which is the same thing as "if x is false"

vsoftco
  • 55,410
  • 12
  • 139
  • 252
1

! is the plan language equivalent of 'not'. it is the shorthand way of saying if (boolval != true), notice the ! in != also means not as in not equal. So the section of code you posted pretty much just says if the timer is NOT active, activate it.

Wobbles
  • 3,033
  • 1
  • 25
  • 51