简体   繁体   English

多次触发时运行一次js功能

[英]Run js function once when fired more than once

I have a Div that uses jQuery to load a file/contents with a javascript function.. 我有一个使用jQuery加载带有javascript函数的文件/内容的Div。

function DoWork() {
    // Do Stuff
}

Let's say the user can reload the Div and pull the same file/contents with the same js function DoWork(). 假设用户可以重新加载Div并使用相同的js函数DoWork()拉出相同的文件/内容。 The problem is, when the file is reloaded, the previous loaded function DoWork() is still running. 问题是,当重新加载文件时,先前加载的函数DoWork()仍在运行。 How can I kill the previous fired DoWork() and restart it? 如何杀死先前解雇的DoWork()并重新启动它?

Javascript is single-threaded, which means only one thing can be executing at a given moment. Javascript是单线程的,这意味着在给定时刻只能执行一件事。 If DoWork is already "running" it's either a) blocking all other JS code, and you have no choice but to let it finish since you have no way to execute any interruption code until it finishes on its own, or b) DoWork is scheduled to fire off on an interval via setTimeout() or setInterval() . 如果DoWork已经“运行”,那么要么a)阻止所有其他JS代码,你别无选择,只能让它完成,因为你无法执行任何中断代码,直到它自己完成,或者b) DoWork被安排通过setTimeout()setInterval()在一个间隔上触发。

If it's the latter case, setTimeout() and setInterval() return an ID. 如果是后一种情况,则setTimeout()setInterval()返回一个ID。 Store that ID somewhere and call clearTimeout(doWork_timeout_id) or clearInterval(doWork_interval_id) according to how you started it. 将ID存储在某处,并根据启动方式调用clearTimeout(doWork_timeout_id)clearInterval(doWork_interval_id)

You can build a simple function that use: setTimeout and then each call to DoWork will call first to: clearTimeout. 您可以构建一个使用:setTimeout的简单函数,然后每次调用DoWork将首先调用:clearTimeout。 I don't really like this solution because you will waste CPU on setTimeout. 我真的不喜欢这个解决方案,因为你会在setTimeout上浪费CPU。 So another option will be to use web worker in DoWork (It will do lots of other good things for you in case you are working with big data as it's running in another thread) - then you get an option to send 'stop' message each time you start the work of DoWork(). 所以另一种选择是在DoWork中使用Web worker(如果你在另一个线程中运行大数据的话,它将为你做很多其他的好事) - 然后你可以选择发送'stop'消息你开始DoWork()工作的时候了。

Are you using ajax to load the div's contents? 你使用ajax加载div的内容吗? if so, the better way is as follows: 如果是这样,更好的方法如下:

var doWorkAjax=null;
function DoWork(){
    if (doWorkAjax) doWorkAjax.abort(); 
    doWorkAjax = $.ajax(url, data, function(result){
        ....
        doWorkAjax=null;
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM