Javascript:单击按钮后退出JavaScript循环 [英] Javascript: exit from javascript loop when button clicked

查看:174
本文介绍了Javascript:单击按钮后退出JavaScript循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript循环,由ajax调用了php函数.我需要通过单击一个按钮来停止该循环. 我尝试使用标签,但这是不可能的:

I've a javascript loop that call by ajax a php function. I need to stop that loop by clicking a button. I tried using labels but it's not possible:

labelName:
for (var counter = 0; counter <= 1000; counter++) {
    ...
    ajax call
    ...
}

$('#button-stop').click(function(event) {
    event.preventDefault();
    break labelName;
});

但是这会导致错误找不到SyntaxError标签".实际上,只有当我输入"break labelName;"时,进入循环错误消失.但是,如果我将其放入click函数中,则无法再次识别标签.

But this make error "SyntaxError label not found". In fact only if I put "break labelName;" into loop error disappears. But if I put that into click function not recognize label again.

我该怎么做?还有其他方法可以通过按钮交互来打破循环吗? 谢谢.

How I can make that? Is any other way to break a loop by a button interaction? Thanks.

推荐答案

您无法以这种方式停止循环.单击按钮后,单击事件"会进入事件循环,并且仅在循环完成后才执行.因此,在您的变体中,无论如何,一千个请求将被发送到服务器.

You are not able to stop the cycle this way. When the button is clicked, 'click event' is put into event loop and it will be executed only after the cycle finishes. So, in your variant, a thousand requests will be sent to a server anyway.

如果要控制发送到服务器的邮件,最好使用间隔:

If you want to control message sending to the server, it is better to use intervals:

var sender = setInterval(function() {
    //ajax here
}, 1000);

$('#button-stop').click(function(event) {
    clearInterval(sender);
});

这篇关于Javascript:单击按钮后退出JavaScript循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆