首页 > 解决方案 > Javascript 阻止多次执行

问题描述

我目前正在使用 Web 框架编写 Python 应用程序。我实现了一个调用 javascript 函数,调用 Python WebService 的表单。这些网络服务非常繁重,所以我想实现一个安全性以避免多次运行 javascript 并在允许另一个调用之前等待 WS 响应。

这是一段 HTML :

<div class="form-group">
    <input onfocusout="ocr_on_fly(false, this)" onfocusin="ocr_on_fly(true, this)" type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
</div>

函数中JS中WS的调用ocr_on_fly

onSelectEnd: function(img, selection){
    if(selection['width'] !== 0 && selection['height'] !== 0){
        $.post({
        url: "http://localhost:5000/pdf/ocr",
        data: {
            data: JSON.stringify({
                selection   : selection,
                fileName    : $('#my-image')[0].src.replace(/^.*[\\\/]/, ''),
                thumbSize   : {width: img.width, height:img.height}
            })
        }

        }).then(function(data) {
                input.value = data['result'];
        });
    }
}

我听说过 setTimeout,但不确定它是否更好,因为我不想在指定时间内阻止脚本的执行。该脚本可能需要 0.1 秒,因为它可能需要 10 秒或更长时间

提前致谢

标签: javascriptweb-services

解决方案


您可以设置一个全局变量,然后在调用脚本时将其设置为true.

然后,当响应完成时,您将其设置为false.

在发出请求之前检查这个变量;如果它已经设置为true,请不要提出请求。


推荐阅读