1

I have a JavaScript functions which calls a PHP function through AJAX. The PHP function has a set_time_limit(0) for its purposes. Is there any way to stop that function when I want, for example with an HTML button event?


I want to explain better the situation: I have a php file which uses a stream_copy_to_stream($src, $dest) php function to retrieve a stream in my local network. The function has to work until I want: I can stop it at the end of the stream or when I want. So I can use a button to start and a button to stop. The problem is the new instance created by the ajax call, in fact I can't work on it because it is not the function that is recording but it is another instance. I tried MireSVK's suggest but it doesn't worked!

4

4 回答 4

0

取决于功能。如果是每次都检查某个条件的while循环,那么您可以添加一个可从脚本外部修改的条件(例如,使其检查文件,并根据需要创建/删除该文件)

然而,这看起来是个坏主意。你为什么要这样做?

于 2012-08-27T15:47:34.370 回答
0
var running = true;

function doSomething(){

       //do something........
}

setInterval(function(){if(running){doSomething()}},2000); ///this runs do something every 2 seconds

在按钮上单击只需设置running = false

于 2012-08-27T15:54:48.887 回答
0

您的代码如下所示:

set_time_limit(0);

while(true==true){//infinite loop

 doSomething(); //your code

}

让我们升级它

set_time_limit(0);

session_start();
$_SESSION['do_a_loop'] = true;

function should_i_stop_loop(){

   @session_start(); 

   if( $_SESSION['do_a_loop'] == false ) {

    //let's stop a loop
    exit();

   }

   session_write_close(); 

}

while(true==true){

 doSomething();

 should_i_stop_loop(); //your new function

}

创建新文件 stopit.php

session_start();
$_SESSION['do_a_loop'] = false;

您现在要做的就是在 stopit.php 文件上创建一个请求(使用 ajax 或其他东西)

根据您的需要编辑代码,这是重点。众多解决方案之一。

对不起我的英语不好

于 2012-08-27T16:03:00.920 回答
0

可悲的是,这是不可能的(有点)。

每次您对 PHP 脚本进行 AJAX 调用时,该脚本都会生成一个自身的新实例。因此,您发送给它的任何内容都将被发送到新操作,而不是您之前启动的操作。

有许多解决方法。

  • 在 AJAX 中使用 readystate 3 创建到 PHP 脚本的非关闭连接,但是跨浏览器不支持该连接,并且可能在 IE 中不起作用(不确定 IE 10)。

  • 研究 PHP 中的套接字编程,它允许您使用一个实例创建一个脚本,您可以多次连接。

  • 让 PHP 检查第三方。IE 有一个脚本在循环中运行,检查文件或数据库,然后连接到另一个脚本来修改该文件或数据库。原始脚本可以通过您写入文件/数据库的内容进行远程控制。

  • 尝试另一种编程语言(这是一个愚蠢的选择,但我是节点的粉丝)。Node.js 非常非常容易地做到这一点。

于 2012-08-27T16:08:40.290 回答