0

I need to create a javascript countdown timer, I've been trying to do it using setInterval method but when I pass the seconds as a parameter it keeps looping so that it only goes down by 1 second then stops. Here is my code:

JavaScript :

var second = 120;
document.getElementById('timer').innerHTML = second;
function setTimer(second)
{
    second--;
    document.getElementById('timer').innerHTML = second;
    return second;
}
second = window.setInterval(setTimer, 1000, second); //Timer for user display

Thanks!

yashhy
  • 2,856
  • 5
  • 31
  • 57
user1830386
  • 71
  • 1
  • 6
  • Take a look to the answers: http://stackoverflow.com/questions/1191865/code-for-a-simple-javascript-countdown-timer – Wilson Jan 03 '14 at 05:09
  • remove the second parameter to setTimer - you want to close over the local second var. – Hafthor Jan 03 '14 at 05:14

3 Answers3

2

just do:

function setTimer(num) {
    //start the interval
    var counter = setInterval(function () {
        document.getElementById('timer').innerHTML = num; //write to div
        num-- || clearInterval(counter); //clear (stop) if its 0
    }, 1000);
}
setTimer(120);

Demo:: jsFiddle

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
0
var second = 120;
var timeOutFunction;
document.getElementById('timer').innerHTML = second;
function setTimer()
{
    second--;
    document.getElementById('timer').innerHTML = second;
    if(second == 0)
        clearInterval(timeOutFunction);
}
timeOutFunction = setInterval(setTimer, 1000); //Timer for user display

http://jsfiddle.net/Jd4tx/

arun15thmay
  • 1,062
  • 1
  • 9
  • 19
0
var array1 = ['one', 'two', 'three', 'four', 'five'];
var array2 = ['two', 'four'];

for (var i = array2.length -1; i >= 0; i--)
   array1.splice(array2[i],1);

console.log(array1);
heyo
  • 19
  • 2