Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force setTimeout to fire its payload earlier than originally set

Tags:

I have developed a small bit of presentation software which consists of slides and assets for each slide. When a slide is rendered all of its assets are looped through and rendered after a delay using the setTimeout method. looks sweet...

Yaaay!, requirements have changed, the presentation is now required to act like a PowerPoint slideshow, the mouse click event will cause the next asset to be rendered to the page immediately.

My question is; is there a way to cause my timeout to fire immediately? I can get and store in a stack the timeoutid as it is returned when the timeout is created. The only other option would be to cancel the timeout and then recreate the element, which is a lot more processing then i want to do, and I dont feel like refactoring my code too much.

Any ideas?

like image 212
lgados Avatar asked Oct 07 '11 15:10

lgados


2 Answers

You could wrap it in a closure like this:

function createTimeout(timeoutHandler, delay) {     var timeoutId;     timeoutId = setTimeout(timeoutHandler, delay);     return {         clear: function() {             clearTimeout(timeoutId);         },         trigger: function() {             clearTimeout(timeoutId);             return timeoutHandler();         }     }; }  var a = new Date();  var timeout = createTimeout(function() { console.log(a); }, 1000); // timeout.clear(); timeout.trigger(); 

Updated (modern js):

let newTimeout = (handler, delay) => {     let id = setTimeout(handler, delay), clear = clearTimeout.bind(null, id);     return {id, clear, trigger: () => (clear(), handler())}; };  let timeout = newTimeout(() => console.log(new Date()), 1000); // timeout.clear(); timeout.trigger(); 
like image 110
Killroy Avatar answered Oct 21 '22 01:10

Killroy


If you set the timer like this:

var timer1 = window.setTimeout(mainFunction,500) 

call it immediately by doing this:

window.clearTimeout(timer1) mainFunction() 

The key is to separate the function from the timer.

like image 22
Diodeus - James MacFarlane Avatar answered Oct 20 '22 23:10

Diodeus - James MacFarlane