Reputation: 751
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.
Upvotes: 0
Views: 65
Reputation: 5061
You are misunderstanding use of addEventListener().
The condition in your checkIf()
is returning instantly. Thus your code is
strt()
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.
Upvotes: 1