diff --git a/doc/api.txt b/doc/api.txt index e6a54c24d5..48e51f4a58 100644 --- a/doc/api.txt +++ b/doc/api.txt @@ -488,6 +488,8 @@ puts("The area of a cirlce of radius 4 is " + area(4)); To schedule execution of callback after delay milliseconds. Returns a +timeoutId+ for possible use with +clearTimeout()+. +Optionally, you can also pass arguments to the callback. + +clearTimeout(timeoutId)+:: Prevents said timeout from triggering. @@ -497,6 +499,8 @@ Prevents said timeout from triggering. To schedule the repeated execution of callback every +delay+ milliseconds. Returns a +intervalId+ for possible use with +clearInterval()+. +Optionally, you can also pass arguments to the callback. + +clearInterval(intervalId)+:: Stops a interval from triggering. diff --git a/src/node.js b/src/node.js index 798849d85f..7dfcc279ba 100644 --- a/src/node.js +++ b/src/node.js @@ -491,17 +491,29 @@ process.Stats.prototype.isSocket = function () { // Timers +function addTimerListener (callback) { + var timer = this; + // Special case the no param case to avoid the extra object creation. + if (arguments.length > 2) { + var args = Array.prototype.slice.call(arguments, 2); + timer.addListener("timeout", function(){ + callback.apply(timer, args); + }); + } else { + timer.addListener("timeout", callback); + } +} GLOBAL.setTimeout = function (callback, after) { var timer = new process.Timer(); - timer.addListener("timeout", callback); + addTimerListener.apply(timer, arguments); timer.start(after, 0); return timer; }; GLOBAL.setInterval = function (callback, repeat) { var timer = new process.Timer(); - timer.addListener("timeout", callback); + addTimerListener.apply(timer, arguments); timer.start(repeat, repeat); return timer; }; diff --git a/test/mjsunit/test-timers.js b/test/mjsunit/test-timers.js index 37d5a0dc82..e0cf6423fe 100644 --- a/test/mjsunit/test-timers.js +++ b/test/mjsunit/test-timers.js @@ -40,6 +40,38 @@ setInterval(function () { clearInterval(this); }, 1000); + +// Single param: +setTimeout(function(param){ + assert.equal("test param", param); +}, 1000, "test param"); + +var interval_count2 = 0; +setInterval(function(param){ + ++interval_count2; + assert.equal("test param", param); + + if(interval_count2 == 3) + clearInterval(this); +}, 1000, "test param"); + + +// Multiple param +setTimeout(function(param1, param2){ + assert.equal("param1", param1); + assert.equal("param2", param2); +}, 1000, "param1", "param2"); + +var interval_count3 = 0; +setInterval(function(param1, param2){ + ++interval_count3; + assert.equal("param1", param1); + assert.equal("param2", param2); + + if(interval_count3 == 3) + clearInterval(this); +}, 1000, "param1", "param2"); + process.addListener("exit", function () { assert.equal(true, setTimeout_called); assert.equal(3, interval_count);