Question


I suddenly bumped into maybe a small problem for anyone who decides to answer this question.
I was trying to do following:

Create

var intrvl; //for interval
function strt() {
     //and set interval
     intrvl = setInterval(writeT,3000);
}
function writeT() {
     //do something here as the interval runs
     checkIf(); //check for the mouse down
}
function checkIf() {
     //here goes the code that checks if mouse is down and if it is
     //then I call another function that begins other useful process
     //I tried
     if (c.addEventListener('click')) { //c is my canvas
          clearInterval(intrvl); //guess clearing the interval yee?
          //and then calling the function I want to call
          startDoing();
     }
}

I want to wait and use that interval until someone clicks on canvas and then run the desired function.
But whenever I click on the canvas the function startDoing() happens to be running but it's too fast comparing with running it without all of this.
How Can I make it work? As I want that firstly created interval not to exist and only the startDoing() run.

Was it helpful?

Solution

You are misunderstanding use of addEventListener().

The condition in your checkIf() is returning instantly. Thus your code is

  1. starting interval timer on invoking strt()
  2. adding click handler as early as interval timer is elapsing for the first time
  3. but also it is instantly stopping interval time er and invoking startDoing() then.

Use it like that instead:

var intrvl;
var clicked = false;

function strt() {
     //and set interval
     intrvl = setInterval(checkIf,3000);
}

function checkIf() {
    if ( clicked ) {
        clearInterval( intrvl );
        startDoing();
    }
}

c.addEventListener('click', function() {
    clicked = true;
} );

This code is instantly registering click handler. It is starting interval timer as soon as strt() is invoked. As soon as mouse has been clicked, the variable clicked is set true to mark this event. Next time your interval timer is triggering it is recognizing preceding click due to checking that variable and starting whatever you want to start.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top