You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript 如何实现事件触发时对应代码仅执行一次?

事件绑定仅触发一次的实现正确性判断

结论

正确的实现为 选项1、选项3、选项4,选项2实现错误。

各选项分析

  • 选项1
    代码直接使用了事件模型内置的once方法,该方法本身的设计目的就是注册仅触发一次的监听器,事件第一次触发后会自动移除对应监听器,后续再触发该事件也不会执行回调,完全符合需求,实现正确。
var EventSource = require("eventsource");
const source = new EventSource();

let callindex = 0;

source.once('event', () =>{
    console.log("called");
});
source.emit('event');
  • 选项2
    代码虽然加了callindex == 0的判断逻辑,但callindex变量从未被修改,每次触发事件时callindex的值始终为0,回调内的打印逻辑每次都会执行,不符合仅执行一次的要求,实现错误。
var EventSource = require("eventsource");
const source = new EventSource();

let callindex = 0;

source.on('event', () =>{
  if(callindex == 0){
    console.log("called");
  }
});
source.emit('event');
  • 选项3
    回调每次执行后都会对callindex做自增操作,第一次触发事件时callindex为0,执行打印逻辑后callindex变为1,后续再触发事件时判断条件不成立,不会执行打印逻辑,符合仅执行一次的需求,实现正确。
var EventSource = require("eventsource");
const source = new EventSource();

let callindex = 0;

source.on('event', () =>{
  if(callindex == 0){
    console.log("called");
  }
  callindex++;
});
source.emit('event');
  • 选项4
    回调执行一次后直接调用removeAllListeners移除了当前event事件的所有监听器,后续再触发该事件不会有任何回调执行,符合仅执行一次的需求,实现正确。
var EventSource = require("eventsource");
const source = new EventSource();

let callindex = 0;

source.on('event', () =>{
    console.log("called");
    source.removeAllListeners('event');
});
source.emit('event');

内容的提问来源于stack exchange,提问作者Niladri Banerjee - Uttarpara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 03:45:02