2

I want to be able to invoke a specific method at specific times. For example.

  • after 10 seconds
  • after 20 seconds
  • after 35 seconds
  • after 50 seconds
  • after 60 seconds
  • after 65 seconds

All times from the same starting point. I was looking at the JQuery Timer module but I don't think this will give it to me.

What is the a good approach to do this in JavaScript / Jquery? Or any plugin available from a CDN.

Thanks.

dublintech
  • 16,815
  • 29
  • 84
  • 115

3 Answers3

4

use functional programming :

var makeIntervals = function(timeList,callback){
 intervals = []
 for(i = 0; i< timeList.length ; i++ ){
  intervals.push(setTimeout(callback,timeList[i]))
 }
 return intervals
}
mpm
  • 20,148
  • 7
  • 50
  • 55
  • 1
    Why do you call this "functional programming"? Also, if you expect `timelist` to be an array, you should not use a for-in-loop. – Bergi Nov 09 '12 at 00:25
  • Learn what higher order functions are. Also i dont see the problem using for-in-loop in my exemple, please explain the issue. – mpm Nov 09 '12 at 00:31
  • @camus why do you need the intervals array? The for loop going around setTimeout() should do it. What does the intervals array give you? – dublintech Nov 09 '12 at 00:33
  • because you might want to clear the "timeouts" with `clearTimeout` function. setTimeout returns an id. – mpm Nov 09 '12 at 00:37
  • @camus See http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays - also bear in mind that in cases when you can use a `for..in` loop, you should always use `hasOwnProperty` to ensure you're not getting a property from the object's prototype (`for(key in myObject) { if (myObject.hasOwnProperty(key)) { ... } }`) – Kelvin Nov 09 '12 at 00:40
3

This code will start timers for all the times you've suggested.

function funcToCall()
{
}

setTimeout(funcToCall, 10 * 1000 );
setTimeout(funcToCall, 20 * 1000 );
setTimeout(funcToCall, 35 * 1000 );
setTimeout(funcToCall, 50 * 1000 );
setTimeout(funcToCall, 60 * 1000 );
setTimeout(funcToCall, 65 * 1000 );
mrk
  • 4,999
  • 3
  • 27
  • 42
2

You could just use setTimeout(), and define your desired intervals in an array:

var method = function() { 
        console.log('did something'); 
    },
    intervals = [10, 20, 35, 50, 60, 65],
    i;

for (i = intervals.length - 1; i >= 0; i--) {
    setTimeout(method, intervals[i] * 1000);
}

Demo: http://jsfiddle.net/kelervin/Lg8P3/

Kelvin
  • 5,227
  • 1
  • 23
  • 36