最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to stop function of javascript by pressing button - Stack Overflow

programmeradmin6浏览0评论

I have created functions that call other functions like

function abc()
{
    def();
}

function def()
{
    xyz();
}

Lets say def() is called and at any moment I have a button

<button>STOP</button>

if I press it the execution terminates that means if the execution is run again it should run again from start.

I have seen other solutions in SO but they show how to pause a loop. Can anyone help me out?

I have created functions that call other functions like

function abc()
{
    def();
}

function def()
{
    xyz();
}

Lets say def() is called and at any moment I have a button

<button>STOP</button>

if I press it the execution terminates that means if the execution is run again it should run again from start.

I have seen other solutions in SO but they show how to pause a loop. Can anyone help me out?

Share Improve this question asked Apr 26, 2017 at 1:57 AlenAlen 1,3016 gold badges24 silver badges45 bronze badges 1
  • You can't stop an already-running function by clicking a button. The button click event won't be processed until the current JS execution finishes. – nnnnnn Commented Apr 26, 2017 at 3:00
Add a ment  | 

1 Answer 1

Reset to default 4

You could use a variable to determine whether your code runs or terminates:

var abort = false;

function abc()
{
    if (abort) {
        return;
    }

    def();
}

function def()
{
    if (abort) {
        return;
    }

    xyz();
}

<button onclick="abort = true">STOP</button>

The only thing you'd have to add is to reset abort back to false whenever you're triggering the main functionality.

发布评论

评论列表(0)

  1. 暂无评论