Good day. To the point. When you run the setTime function, we pass input to it, where the time is displayed. question. when re-called through a timer, obj is not defined. and even if the inputs through the var to define does not work. only in this way. here code

var id_inter; var go = true; function setTime(obj) { data = new Date() hours = data.getHours(); mins = data.getMinutes(); secs = data.getSeconds(); if (hours < 10) { hours = "0" + hours; } if (mins < 10) { mins = "0" + mins; } if (secs < 10) { secs = "0" + secs; } time = hours + ":" + mins + ":" + secs; obj.value = " " + time; id_inter = setTimeout('setTime(obj)', 1000); } function stopTime(obj) { clearTimeout(id_inter); obj.value = ""; } function times(input_form) { if (go) { setTime(input_form); go = false; document.data.start.value = "Стоп"; } else { stopTime(input_form); go = true; document.data.start.value = "Старт"; } } 

If you write instead

 obj.value = " " + time; id_inter = setTimeout('setTime(obj)', 1000); 

So:

 inputs = obj; id_inter = setTimeout('setTime(inputs)', 1000); 

then it works.

Why?

https://jsfiddle.net/jL3fhLd3/4/

  • would have written even better in which code does not work. and what does not suit this option? - Alexey Shimansky
  • Corrected. Arranges. Just wondering why. - Ilya Balabuev
  • one
    Interesting behavior. In general, personally, I would pass arguments differently, for example, according to the docks, setTimeout(func / code, delay[, arg1, arg2...]) would write like this: id_inter = setTimeout(setTime, 1000, obj); ..... so it works. But the behavior is interesting .. Wait until someone answers. - Alexey Shimansky

1 answer 1

When you write setTimeout('setTime(obj)', 1000); - your setTime(obj) is executed in the global scope, where there is no obj .

When you write inputs = obj , you create a global variable, that's why setTimeout('setTime(inputs)', 1000); works. But in the case of several timers, everything breaks down - because there is only one global variable.

It is correct to pass to setTimeout not a string - but a function:

 setTimeout(function() { setTime(obj); }, 1000); 

Or, more briefly, if only fresh browsers are interested:

 setTimeout(() => setTime(obj), 1000); 

You can also use the setTimeout form with passing additional arguments:

 setTimeout(setTime, 1000, obj); 
  • for sure. and after all, recently two questions were about setTimeout and their scope. I’ve got a bit of a head: - / - Alexey Shimansky
  • @ Alexey Shimansky is nothing, I’m also full of holes (see update) :-) - Pavel Mayorov