代码之家  ›  专栏  ›  技术社区  ›  hipsterstomper69

当一个方法花费的时间超过预期时,是否使用Javascript方法来提醒用户?[闭门]

  •  -1
  • hipsterstomper69  · 技术社区  · 4 年前

    我有一些socket.io发射,我想在它们需要很长时间才能从服务器返回承诺时提供处理。但我也不想直接把它们暂停。我在一些网站上看到过这样的情况,加载微调器会在10秒左右的时间后添加“这似乎比平常要花更长的时间”文本。

    如何将超时样式的方法添加到Javascript函数中,该函数将在一定时间后执行某些操作,但不会取消原始方法?

    1 回复  |  直到 4 年前
        1
  •  1
  •   TheBritishAreComing    4 年前

    除非您具有全局作用域,否则需要传入两个处理程序

    function doSocketRequest(normalHandler, tooLongHandler) {
        let timer = null;
        
        // set timeout to 5 seconds, if we hit it then trigger "tooLongHandler"
        timer = setTimeout(tooLongHandler, 5000);
        
        // When we receive our socket response for the event, clear the time and trigger "normalHandler"
        socket.on('some_event_response', (response) => {
            clearTimeout(timer);
            normalHandler(response)
        });
        
        // Emit to server
        socket.emit('some_event', ...etcetc);   
    }