skip to Main Content

So I want to rerun my function with updated values based on an event function.

Because i’m trying to use this javascript as a content-script, while statements don’t work as they just spam outputs and crash the page.

No if statements as it will just go through the code before the event and not repeat the if statement after I trigger the event. Here is basically what I’m trying to do.

function outer(value) {
  function inner() {
     outer(value); //rerun the function
     //then cancel this instance of the function
  
  }
  window.addEventListener('keydown', function(event) {
  //call function based off of evennt
  inner()
  }
}

I’ve tried all the ways to exit functions, but things like setInterval count as functions, so if I have a if statement be checked in intervals, it will only exit the setInterval.

2

Answers


  1. What do you want to update in this function?
    If you want to do something different in the keydown event, just delete inner and remove the eventListener at the right time.
    ex:

    var count = 0 // for example
    function outer(value) {
      window.addEventListener('keydown', handleEvent)
    }
    
    function handleEvent(event){
      event.stopPropagation();
      //call function based off of evennt
      count++
      removeKeyDown()
    }
    
    function removeKeyDown(){
      if (count > 3) { // just for remove
        window.removeEventListener('keydown', handleEvent)
      }
    }
      
    
    Login or Signup to reply.
  2. function outer(value) {
     function inner() {
      console.log("Function rerun with value:", value);
     }
    function handleEvent(event) {
      if (event.key === "Enter") {
        inner();
        window.removeEventListener('keydown', handleEvent);
        listener if you want to stop after one execution
      }
    }
    window.addEventListener('keydown', handleEvent);
    }
    outer(42);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search