用变量传递回调

时间:2016-01-31 20:39:41

标签: javascript node.js timer callback

嘿,我认为这是个好主意, 不知怎的,它不起作用。我可以让它运作吗? 或者它被认为是不好的做法?

我有一种数学教室应用程序,老师可以向学生发送问题,然后他们回答。

这个想法是:在问题显示前倒数5秒, 然后发送问题, 然后倒计时以跟踪学生使用的最长时间。

我以为我不需要两个单独的倒计时功能,因为我可以传递两个函数(一个包含在每个滴答处做的事情,另一个是实际的cb)。

但它崩溃了count is not defined

任何提示?

socket.on('sendTestProblem', function(msg) {
    countdown(function() {
        socket.broadcast.to(socket.room).emit('timer', { countdown: count });  // crash on this line
      },
      function broadcastProblemToStudents() {
      socket.broadcast.to(socket.room).emit('testProblem', {problem: msg.problem, timeLimit: timeLimit});
      socket.emit('problemSentToStudents');

      // after pre-countdown, start countdown for max answering time
      countdown(function countdownForAnswers() {
        io.in(socket.room).emit('timeLimit', {timeLimit: count});
      }, function timeOver() {
        io.in(socket.room).emit('timeOver');
      }, msg.timeLimit);
    })
  });

  function countdown(emit, cb, timeLimit) {
    console.log('countdown');
    var count = timeLimit || COUNTDOWN;
    var countdown = setInterval(function() {
      emit();  // emit this on every tick
      count--;
      if (count == 0) {
        clearInterval(countdown);
        cb();  // call this on 0
      }
    }, 1000);
  }

1 个答案:

答案 0 :(得分:2)

你在倒计时功能的范围内声明了count变量,并且它不会出现在" emit"打回来。您应该将其作为参数传递或在共享范围中声明

    countdown(function(count) {
            socket.broadcast.to(socket.room).emit('timer', { countdown: count });
          },
...

    emit(count);