如何不断调用函数

时间:2017-06-27 14:52:27

标签: javascript node.js

我希望能够连续运行此代码,以便我调用的函数始终检查输入是真还是假

index.js

io.on('connection', function(socket) {
var entered = require('./main.js').onProximityBoolean; /// i want this to continuously be checking itself
   if (entered == true) {
     socket.emit('enterProximity');
   }
}

main.js

var enter = false;
function onProximityBoolean(enter) {
  if (enter === true) {
    console.log(enter);
    return true;
  } else {
    return false;
  }
}

function isWithinBounds() {
  //inside here is sensor code that says if the object comes close 
  //then enter will be true else enter will be false
  //this part accurately redefines the onProximityBoolean
}
module.exports = {
  onProximityBoolean: onProximityBoolean(enter)
};

3 个答案:

答案 0 :(得分:2)

您可能希望使用setter / getter实现 observer

INCLUDE Irvine32.inc

ABS PROC
cmp ebx,0       ;compare ebx to zero
jle L1          ;Jump if less then or equal to zero
mov eax, ebx    ;copy ebx to eax, means eax is positive
Jmp L2          ;jumps to label return
L1:neg ebx      ;negates ebx    
mov eax,ebx     ;copy neagted ebx to eax        
L2:ret
ABS ENDP

.DATA
arrayW SDWORD 3, -2, 5, 7, 2, 9, -11, 32, -19, 18, 17, 15, -5, 2, 3, 1, -21, 27,-29, 20

.CODE
main PROC

    mov esi, OFFSET arrayW      ;address of arary
    mov ecx, LENGTHOF arrayW    ;loop counter

top:
    mov ebx,[esi]               ; move first element of arrayw to ebx
    call ABS                    ; calls procedure abs and gets the eax value
    call Writeint               ; displays eax  
    add esi, TYPE arrayW        ;points next element in array
    loop top                    ;loop goes to the top
    call clrscr

    exit
main ENDP

END main

所以你可以这样做:

$('.hiddenDV').hide();
$(".add-another").click(function() {
  $(this).parents('.row').nextAll('.hiddenDV:lt(2)').slideDown();
});
$(".remove").click(function() {
  $(this).parent('.row').hide().prev('.hiddenDV').slideUp();
  $(this).closest(".hiddenDV").find('input[type="text"]').val('');
  $(this).closest(".hiddenDV").prev(".hiddenDV").find('input[type="text"]').val('');
});

或者使用setInterval来定期检查:

"main.js";
var state=false;
var handlers=[];
module.exports={
  get proximityBoolean(){
     return state;
  },
  set proximityBoolean(value){
     if(value!==state){
       state=value;
       handlers.forEach(func=>func(value));
  },
  observe(func){
    handlers.push(func);
  }
}

答案 1 :(得分:0)

尝试使用setInterval()方法。你可以使用while(true)循环,但这会使代码变慢,所以我建议你做的是:

io.on('connection', function(socket){
    setInterval(function(socket) {
       var entered = require('./main.js').onProximityBoolean;
          if (entered == true) {
             socket.emit('enterProximity');
             } 
      },1000);}); //after 1 second the function will be called [1000ms]

答案 2 :(得分:0)

我认为你应该使用cron工作。这里the npm repo and example of use