如何使用clearInterval?

时间:2019-02-26 15:24:50

标签: node.js

我是nodejs的新手,并尝试将消息发送到服务器。

当我输入1时,它将每3秒钟向服务器设置一条消息。当我输入2时,它将停止发送消息。

但是,当我输入2时,它将一直向服务器发送消息。我应该如何使用clearInterval

这是脚本。

var WebSocket = require('ws');
var ws = new WebSocket("ws://localhost:8075");

ws.onopen = ('connect', function(connect) {
  let obj={};
  obj.body='connect';
  ws.send(JSON.stringify(obj));
});

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (message) {
    if (message.trim() == '1') {
            var setintv = setInterval(function () {
                let obj2 = {};
                obj2.name = 'data'
                message = '123';
                obj2.body = message;
                ws.send(JSON.stringify(obj2), console.log.bind(null, 'Sent : ', message));
        }, 3000);
}else if(message.trim() == '2') {
    clearInterval(setintv);
}
else {
    let obj = {};
    obj.name = 'data'
    message = message.trim();
    obj.body = message;
    ws.send(JSON.stringify(obj), console.log.bind(null, 'Sent : ', message));
}
});

1 个答案:

答案 0 :(得分:0)

变量setintv在调用clearInterval的块中不可用。但是,如果您将其声明为全局变量,则为:

var WebSocket = require('ws');
var ws = new WebSocket("ws://localhost:8075");

ws.onopen = ('connect', function(connect) {
  let obj={};
  obj.body='connect';
  ws.send(JSON.stringify(obj));
});

var setintv = null;

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (message) {
    if (message.trim() == '1') {
        // Save for later use.
        setintv = setInterval(function () {
                let obj2 = {};
                obj2.name = 'data'
                message = '123';
                obj2.body = message;
                ws.send(JSON.stringify(obj2), console.log.bind(null, 'Sent : ', message));
        }, 3000);
}else if(message.trim() == '2') {
    if (setintv !== null) {
        clearInterval(setintv);
        setintv = null; // We're done with this now.
    }
}
else {
    let obj = {};
    obj.name = 'data'
    message = message.trim();
    obj.body = message;
    ws.send(JSON.stringify(obj), console.log.bind(null, 'Sent : ', message));
}
});