user2810762
user2810762

Reputation: 395

JS remove and add class timing function

Below is some js that i have no idea how to modify to do what i want. Instead of onclick i need the js to activate after a delay of 40 seconds.

// retrieve the element
element = document.getElementById("ani");

// reset the transition by...
element.addEventListener("click", function(e){
e.preventDefault;

// -> removing the class
element.classList.remove("delay-1");

// -> triggering reflow /* The actual magic */
// without this it wouldn't work. Try uncommenting the line and the transition won't be         retriggered.
element.offsetWidth = element.offsetWidth;

// -> and re-adding the class
element.classList.add("delay-1");
}, false);

Upvotes: 3

Views: 4390

Answers (3)

Karim AG
Karim AG

Reputation: 2193

use setTimeout function:

setTimeout(function() {
    // retrieve the element
    element = document.getElementById("ani");

    // reset the transition by...
    element.addEventListener("click", function(e){
    e.preventDefault;

    // -> removing the class
    element.classList.remove("delay-1");

    // -> triggering reflow /* The actual magic */
    // without this it wouldn't work. Try uncommenting the line and the transition won't be retriggered.
    element.offsetWidth = element.offsetWidth;

    // -> and re-adding the class
    element.classList.add("delay-1");
    }, false);
}, 40000);

Upvotes: 0

Oskar
Oskar

Reputation: 134

Use the function setTimeout.

as seen in e.g. How do I delay a function call for 5 seconds?

In your case:

// retrieve the element
element = document.getElementById("ani");

// reset the transition by...
element.addEventListener("click", function(e){
  e.preventDefault;

  //introducing a delay of 40 seconds.
  setTimeout(function() {
    // -> removing the class
    element.classList.remove("delay-1");

    // -> triggering reflow /* The actual magic */
    // without this it wouldn't work. Try uncommenting the line and the transition won't be         retriggered.
    element.offsetWidth = element.offsetWidth;

    // -> and re-adding the class
    element.classList.add("delay-1");
  }, 40 * 1000);
}, false);

Upvotes: 0

lshettyl
lshettyl

Reputation: 8181

Use setTimeout to invoke a method/task after a specified number of milliseconds.

setTimeout(function() {
    //your code/function here
}, (40*1000)); //40 seconds

Upvotes: 8

Related Questions