简体   繁体   中英

How to kill another function

I have a function that does request to API when the video is finished:

 video.addEventListener('ended', example);
 var example = function () {
   VK.api('video.get', { owner_id: 123 }, function(data) { 
     /**...*/ 
   }
 }

And also I have a replay button (shows when video is finished), which the user can click faster than the response comes from API. And now I need to kill my function. How I can do it?

Link to API: https://vk.com/dev/video.get

There don't seems to be any method to cancel a all from this api.
So either you analyse the code to see how is handled that call (Can't do it for you because we need an auth).

I'd say that your best bet is to set a boolean flag to true while making the call and to false when asking for replay :

 //Our flag var userCanceledCalled = false; var example = function () { document.querySelector('span').innerHTML = "new example should be called in few seconds"; //Set it to fals at call userCanceledCalled = false; VK.api('video.get', { owner_id: 123 }, function(data) { if(!userCanceledCalled){ alert(data); } }); } function replay(){ //Set it to true on user action document.querySelector('span').innerHTML = "new example as been canceled"; userCanceledCalled = true; } var b = document.querySelectorAll('button'); b[0].addEventListener('click', example); b[1].addEventListener('click', replay); var VK={api: function(data, useless, fn){setTimeout(function(){fn(data)}, 3000)}}; 
 <button>Call a new Example</button></br> <button>Replay</button> <span id="log"></span> 

There are two approaches:

  1. Cancel the ongoing request
  2. Prevent the callback function from doing work

I have no idea how to do 1. but you can probably ask at the Vkontakte issue tracker https://vk.com/bugs

As for the second one, you can check if the user has already clicked on replay button by the time the response comes back and turn your callback into a noop:

video.addEventListener('ended', function () {
    VK.api('video.get', { owner_id: 123 }, function (data) {

        // Let's check if user has pressed the replay button and
        // if yes then we abort the function:
        if (userHasPressedReplay) { return; }

        /**...*/ 
    };
});

This is not ideal because the request still hits the server... but it prevents execution of the callback function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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