Samuel Chalk
Samuel Chalk

Reputation: 11

Executing two functions in the same onclick event but running one only once

I'm trying to get an image to run two javascript functions at the same time, the problem is that I want the changeImg() function to run continually with each click but only execute the clock() function once. (So that it starts the timer).
<img id="emotion" src="Target.jfif" width="50" onclick="changeImg();clock(); this.onclick=null;"/>

This is my changeImg() script:

{
var x = Math.floor(Math.random()*900);
var y = Math.floor(Math.random()*900);


var obj = document.getElementById("emotion");

obj.style.top = x + "px";
obj.style.left = y + "px";


 }

And this is my clock() script:

   function clock() {
     myTimer = setInterval(myClock, 1000);
     var c = 30;

     function myClock() {
       document.getElementById("demo").innerHTML = --c;
       if (c == 0) {
         clearInterval(myTimer);
         alert("Reached zero");
       }
     }
   }

Upvotes: 0

Views: 46

Answers (2)

patrickfv
patrickfv

Reputation: 36

instead of passing null to onclick pass the function changeImg

onclick="changeImg();clock();this.onclick=changeImg;"

I don't know about good practices but it works without changing your code too much

Upvotes: 0

Barmar
Barmar

Reputation: 780724

Have clock() check if the timer is already set, and return.

function clock() {
  if (myTimer) { // clock already started
    return;
  }
  myTimer = setInterval(myClock, 1000);
  var c = 30;

  function myClock() {
    document.getElementById("demo").innerHTML = --c;
    if (c == 0) {
      clearInterval(myTimer);
      alert("Reached zero");
    }
  }
}

Upvotes: 1

Related Questions