Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  35] [ 3]  / answers: 1 / hits: 41821  / 11 Years ago, thu, june 13, 2013, 12:00:00

I am relatively novice to javascript. I have written a simple counter program that starts count down from 10 till it reaches 1.



  <script type=text/javascript>
function countDown(secs) {
var element = document.getElementById(status);
element.innerHTML = Please wait for +secs+ seconds;
if(secs < 1) {
clearTimeout(timer);
element.innerHTML = '<h2>Countdown Complete!</h2>';
element.innerHTML += '<a href=#>Click here now</a>';
}
secs--;
---> **var timer = setTimeout('countDown('secs')',1000);**
}
</script>
<div id=status></div>
<script type=text/javascript>countDown(10);</script>


Then I tried passing parameter as '+secs+' to the countDown function.



var timer = setTimeout('countDown('+secs+')',1000);


Above change works.



My question is why should I need to pass parameter as '+secs+' and NOT only 'secs' ?
What difference does it make?


More From » settimeout

 Answers
42

use



var timer = setTimeout(function(){
countDown(secs)
},1000);


or



var timer = setTimeout('countDown('  + secs + ')',1000);


In your case the problem was your were using string concatenation with a variable without + sign (my second example) with will cause a syntactical error


[#77646] Wednesday, June 12, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tristab

Total Points: 735
Total Questions: 106
Total Answers: 96

Location: Grenada
Member since Sun, Dec 20, 2020
3 Years ago
tristab questions
Sat, Sep 25, 21, 00:00, 3 Years ago
Sun, Jan 31, 21, 00:00, 3 Years ago
Wed, Dec 2, 20, 00:00, 4 Years ago
Fri, Oct 23, 20, 00:00, 4 Years ago
;