简体   繁体   English

如何停止Javascript函数执行?

[英]how to stop Javascript function execution?

My program has two buttons. 我的程序有两个按钮。 One is for execute other program by using jquery load function. 一种是通过使用jquery加载功能来执行其他程序。 Whenever I click execute button, it runs some other program abc.php using load function for n times, with some time gap like k mins. 每当我单击“执行”按钮时,它都会使用加载功能运行其他程序abc.php达n次,间隔为k分钟。 These n and k will be filled with html inputs. 这些n和k将用html输入填充。 Using jquery, will retrieve these and passing to that program file in url. 使用jquery,将检索这些并将其传递到URL中的该程序文件。

To call this function setTimeout was used. 为了调用此函数,使用了setTimeout

Second one is for cancel execution. 第二个是取消执行。

Now my doubt is, suppose I want to stop that execution with cancel button. 现在我的疑问是,假设我想使用“取消”按钮停止执行。 Is there any way to stop it ? 有什么办法阻止它吗?

I would do this using boolean variable. 我会使用boolean变量来做到这一点。

For example: Consider a method, perform logging. 例如:考虑一种方法,执行日志记录。

fun () {
  console.log("prints");
}

I would change it has 我会改变它

fun (isExecute) {
  if (isExecute) {
   console.log("prints");
  }
}

Run fun (true); 运行 fun (true); cancel fun (false); 取消 fun (false);


Updates: 更新:

It seems you use setTimeout() , then it is too easy without above approach. 似乎您使用setTimeout() ,那么如果没有上述方法,那就太容易了。

Run var inter = setTimeout(fun); 运行 var inter = setTimeout(fun); cancel clearTimeout(inter); 取消 clearTimeout(inter);

FYI: The reason for assigning to a variable inter is then only you can clear this time interval. FYI:之所以赋值给一个变量inter 是那么只有你可以清除该时间间隔。

set time for function: 设置功能时间:

timer = setTimeout(function(){$('#submenu').hide();},5000);

stop a function 停止功能

clearTimeout(timer);

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

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