1 /* Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
16 var Timer = process.binding(process.binding.timer);
18 var util = require('util');
20 var TIMEOUT_MAX = 2147483647; // 2^31-1
23 function Timeout(after) {
25 this.isrepeat = false;
31 Timer.prototype.handleTimeout = function() {
32 var timeout = this.timeoutObj; // 'this' is Timer object
33 if (timeout && timeout.callback) {
35 if (!timeout.isrepeat) {
42 Timeout.prototype.activate = function() {
44 var handler = new Timer();
51 handler.timeoutObj = this;
52 this.handler = handler;
54 handler.start(this.after, repeat);
58 Timeout.prototype.close = function() {
59 this.callback = undefined;
61 this.handler.timeoutObj = undefined;
63 this.handler = undefined;
68 exports.setTimeout = function(callback, delay) {
69 if (!util.isFunction(callback)) {
70 throw new TypeError('Bad arguments: callback must be a Function');
74 if (delay < 1 || delay > TIMEOUT_MAX) {
78 var timeout = new Timeout(delay);
80 // set timeout handler.
81 if (arguments.length <= 2) {
82 timeout.callback = callback;
84 var args = Array.prototype.slice.call(arguments, 2);
85 timeout.callback = function() {
86 callback.apply(timeout, args);
96 exports.clearTimeout = function(timeout) {
97 if (timeout && timeout.callback && (timeout instanceof Timeout))
100 throw new Error('clearTimeout() - invalid timeout');
104 exports.setInterval = function(callback, repeat) {
105 if (!util.isFunction(callback)) {
106 throw new TypeError('Bad arguments: callback must be a Function');
110 if (repeat < 1 || repeat > TIMEOUT_MAX) {
113 var timeout = new Timeout(repeat);
115 // set interval timeout handler.
116 if (arguments.length <= 2) {
117 timeout.callback = callback;
119 var args = Array.prototype.slice.call(arguments, 2);
120 timeout.callback = function() {
121 callback.apply(timeout, args);
124 timeout.isrepeat = true;
131 exports.clearInterval = function(timeout) {
132 if (timeout && timeout.isrepeat)
135 throw new Error('clearInterval() - invalid interval');